开发者

Linq - how to combine two enumerables

How to modify version 2 to produce the same r开发者_如何转开发esult 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] };


Do you mean this?

var query = from index in Enumerable.Range(0,a.Length)
            select new { A = a[index], 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.


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] };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜