Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from List of string array to List of objects

Tags:

arrays

c#

list

If I have a simple class that looks like this:

public string Param1 { get; set; }
public string Param2 { get; set; }
public SimpleClass (string a, string b) { Param1 = a; Param2 = b; }

List of string array returned from another class:

var list = new List<string[]> {new[] {"first", "second"}, new[] {"third", "fourth"}};

Is there a more efficient way using C# to end up with List<SimpleClass> without doing something like:

var list1 = new List<SimpleClass>();
foreach (var i in list)
{          
    var data = new SimpleClass(i[0], i[1]);
    list1.Add(data);         
}
like image 234
hello Avatar asked Oct 18 '16 22:10

hello


People also ask

Can we convert list of String to list of object?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .

Can we convert String array to list?

We can easily convert String to ArrayList in Java using the split() method and regular expression.


2 Answers

You can use Linq:

var simpleClassList = originalList.Select(x => new SimpleClass(x[0], x[1])).ToList()
like image 196
rualmar Avatar answered Sep 30 '22 10:09

rualmar


As was said by @rualmar you can use linq. But you also can overload implicit operator. For example

public static implicit operator SimpleClass(string[] arr)
{
    return new SimpleClass(arr[0], arr[1]);
}

and after that you can write this

var list = new List<SimpleClass> { new[] { "first", "second" }, new[] { "third", "fourth" } };
like image 25
Eins Avatar answered Sep 30 '22 11:09

Eins