2

I have 2 types of string: Mer and Spl

// Example
string testMer = "321|READY|MER";
string testSpl = "321|READY|SPL";

Then I will split them:

var splitMer = testMer.Split('|');
var splitSpl = testSpl.Split('|');

I have an object to save them

public class TestObject
{
    public int id { get; set; }
    public string status { get; set; }
    public string type { get; set; }
}

Question: How to convert the Array into the TestObject?

1
  • new TestObject { id = Int.Parse(splitMer[0]), status = splitMer[1], type = splitMer[2] }? Commented Feb 19, 2014 at 5:59

4 Answers 4

5
var converted = new TestObject 
               {
                  id = int.Parse(splitMer[0]),
                  status = splitMer[1],
                  type = splitMer[2]
               };

You will need to add some error checking.

Sign up to request clarification or add additional context in comments.

Comments

4
var values = new List<string> { "321|READY|MER", "321|READY|SPL" };

var result = values.Select(x =>
        {
            var parts = x.Split(new [] {'|' },StringSplitOptions.RemoveEmptyEntries);
            return new TestObject
            {
                id = Convert.ToInt32(parts[0]),
                status = parts[1],
                type = parts[2]
            };
        }).ToArray();

You just need to use object initializers and set your properties.By the way instead of storing each value into seperate variables, use a List.Then you can get your result with LINQ easily.

Comments

3
var splitMer = testMer.Split('|');

var testObj = new TestObject();

testObj.Id = Int32.Parse(splitMer[0]);
testObj.Status = splitMer[1];
testObj.type = splitMer[2];

2 Comments

object initializers make job simpler :)
Also you can create an array of testObj as var testObj[size]= new TestObject(); for storing multiple objects.
2

How about adding a Constructor to your Class that takes a String as a Parameter. Something like this.

public class TestObject
{
    public int id { get; set; }
    public string status { get; set; }
    public string type { get; set; }

    public TestObject(string value)
    {
        var valueSplit = value.Split('|');
        id = int.Parse(valueSplit[0]);
        status = valueSplit[1];
        type = valueSplit[2];

    }
}

Usage:

TestObject tst1 = new TestObject(testMer);
TestObject tst2 = new TestObject(testSpl);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.