[英]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. 如何修改版本2以产生与版本1相同的结果,因为在版本2中我得到了克里特产品。
int[] a = { 1, 2, 3 };
string[] str = { "one", "two", "three" };
Version 1 版本1
var q =
a.Select((item, index) =>
new { itemA = item, itemB = str[index] }).ToArray();
version 2 版本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. 这在函数式编程中称为zip
。 It is now available as a .NET 4.0 built-in but you can write it yourself. 它现在可以作为内置的.NET 4.0使用,但您可以自己编写。 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. 虽然它在4.0中,但是这个功能可以很容易地自己实现。
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; 版本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] };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.