Linq - how to combine two enumerated numbers

How to change version 2 to get the same result as version 1, because in version 2 I get a cretin product.

int[] a = { 1, 2, 3 }; string[] str = { "one", "two", "three" }; 

Version 1

 var q = a.Select((item, index) => new { itemA = item, itemB = str[index] }).ToArray(); 

version 2

 var query = from itemA in a from index in Enumerable.Range(0,a.Length) select new { A = itemA, B = str[index] }; 
+4
source share
3 answers

Do you mean this?

 var query = from index in Enumerable.Range(0,a.Length) select new { A = a[index], B = str[index] }; 
+4
source

In functional programming, this is called zip . Now it is available as embedded .NET 4.0, but you can write it yourself. Their announcement:

 public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func); 

You will get something like:

 var results = a.Zip(b, (x,y) => new { itemA = x, itemB = y }); 

Although it is in 4.0, the function can be easily implemented independently.

+4
source

You should not.

There is nothing wrong with version 1; you should not always try to use query understanding syntax just for fun.

If you really want to do this, you can write the following:

 from i in Enumerable.Range(0, a.Length) select new { A = a[i], B = b[i] }; 
-one
source

All Articles