Convert from a list of array of strings to a list of objects

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 the array of strings returned from another class:

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

Is there a more efficient way to use C # in the end using 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); } 
+5
source share
2 answers

You can use Linq:

 var simpleClassList = originalList.Select(x => new SimpleClass(x[0], x[1])).ToList() 
+8
source

As @rualmar said, you can use linq. But you can also overload the implicit statement. for instance

 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" } }; 
+3
source

Source: https://habr.com/ru/post/1258430/


All Articles