简体   繁体   中英

Linq - how to combine two enumerables

How to modify version 2 to produce the same result as version 1,because in version 2 i am getting cretesian 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] };

This is referred to as zip in functional programming. It is now available as a .NET 4.0 built-in but you can write it yourself. Their declaration is:

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

You result would be something like:

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

Although it's in 4.0, the function can easily be implemented yourself.

Do you mean this?

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

You shouldn't.

There is nothing wrong with version 1; you shouldn't always try to use query comprehension syntax just for the fun of it.

If you really want to do, you could write the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM