Update:
Eric Lippert recently posted on this: http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx
It's especially interesting because he's posted the source for the new extension in C#4:
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
return ZipIterator(first, second, resultSelector);
}
private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>
(IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
using (IEnumerator<TFirst> e1 = first.GetEnumerator())
using (IEnumerator<TSecond> e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
yield return resultSelector(e1.Current, e2.Current);
}
Original answer:
Are you referring to a join?
from x in seq1
join y in seq2
on x.foo equals y.foo
select new {x, y}
There is also pLinq - which executes linq statements in parallel (across multiple threads).
Edit:
Ah - thanks for clarifying the question, though I really don't think my answer deserved a vote down.
It sounds like what you want is something like:
from x in seq1
join y in seq2
on x.Index equals y.Index
select new {x.Foo, y.Bar}
Unfortunately you can't do that with Linq - it extends IEnumerable
, which only really has current
and next
properties, so no index property.
Obviously you can do this easily in C# with a nested for-loop and an if block, but you can't with Linq I'm afraid.
The only way to mimic this in linq syntax is to artificially add the index:
int counter = 0;
var indexed1 = (
from x in seq1
select { item = x, index = counter++ } ).ToList();
//note the .ToList forces execution, this won't work if lazy
counter = 0;
var indexed2 = (
from x in seq2
select { item = x, index = counter++ } ).ToList();
var result =
from x in indexed1
join y in indexed2
on x.index = y.index
select new {x.item.Foo, y.item.Bar}