tags:

views:

178

answers:

4

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] };
+2  A: 

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.

Frank Krueger
A: 

There is no support for this Select method using LINQ Query Expressions. Just out of curiosity why do you want to rewrite it?

Stan R.
+3  A: 

Do you mean this?

var query = from index in Enumerable.Range(0,a.Length)
            select new { A = a[index], B = str[index] };
Konamiman
this should work of course.
Stan R.
A: 

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