Split multiple lines into a list of objects in C #

I have the following code:

public class Info { public string Name; public string Num; } string s1 = "a,b"; string s2 = "1,2"; IEnumerable<Info> InfoSrc = from name in s1.Split(',') from num in s2.Split(',') select new Info() { Name = name, Num = num }; List<Info> listSrc = InfoSrc.ToList(); 

I would like my listSrc result listSrc contain two Info elements whose Name and Num properties:

 a, 1 b, 2 

However, the code shown above leads to four elements:

 a, 1 a, 2 b, 1 b, 2 
+5
source share
2 answers

You can use Enumerable.Zip :

 IEnumerable<Info> InfoSrc = s1.Split(',') .Zip(s2.Split(','), (name, num) => new Info(){ Name = name, Num = num }); 

If you need to map more than two collections for properties, you can bind multiple Zip along with an anonymous type by holding the second and third:

 IEnumerable<Info> InfoSrc = s1.Split(',') .Zip(s2.Split(',').Zip(s3.Split(','), (second, third) => new { second, third }), (first, x) => new Info { Name = first, Num = x.second, Prop3 = x.third }); 

Here, I hope, a more readable version:

 var arrays = new List<string[]> { s1.Split(','), s2.Split(','), s3.Split(',') }; int minLength = arrays.Min(arr => arr.Length); // to be safe, same behaviour as Zip IEnumerable<Info> InfoSrc = Enumerable.Range(0, minLength) .Select(i => new Info { Name = arrays[0][i], Num = arrays[1][i], Prop3 = arrays[2][i] }); 
+6
source

Assuming the number of items in each list is equal, it looks like you are trying to zip them together ...

 s1.Split(',').Zip(s2.Split(','), (name, num) => new Info{Name = name, Num = num}) 
+5
source

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


All Articles