Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array to object

Tags:

c#

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?

like image 746
king jia Avatar asked Aug 14 '26 10:08

king jia


2 Answers

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

You will need to add some error checking.

like image 192
nvoigt Avatar answered Aug 17 '26 00:08

nvoigt


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.

like image 29
Selman Genç Avatar answered Aug 17 '26 01:08

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!