Question

HI.

This is what I want to do:

    str2 = "91";
    str1 = "19";
    var testQuery = from c1 in str1
                    from c2 in str2
                    select new {c1, c2};
    foreach (var enumerable in testQuery)
    {
        Console.WriteLine(enumerable.c1 + " | " + enumerable.c2);
    }

What I want:

9 | 1
1 | 9

What I really get:

1 | 9
1 | 1
9 | 9
9 | 1

The code is a pure example. It might iterate through arrays or some other collection. It will also do some other things, but they are irrelevant to this problem.

Without linq, I could do something like this:

    for (int i = 0; i < str1.Length -1; i++)
    {
        Console.WriteLine(str1[i] + " | " + str2[i]);
    }

But I want a query that can do everything I need instead.

Do I really have to create my own enumerator method that uses yield to create what I want?

EDIT: per request: An example of what I'd like to be able to do:

    str1 = "91";
    str2 = "19";

    char[] digitX = str1.ToString().Reverse().ToArray();
    char[] digitY = str2.ToString().Reverse().ToArray();

    var q = digitX.Select((c1, i) => new {c1 = c1 - '0', c2 = digitY[i] - '0' });

I'd like to pull the reverse etc. in the actual query. So I keep it all gathered. Extra: Being able to pull this with the sql-like sugarcoated syntax, I'd be thrilled. Instead of a method chain, that is.

Was it helpful?

Solution

You can use:

var testQuery = str1.Select( (c,i) => new {c, str2[i]} );

Edit:

Given your new question, you should be able to do:

var q = str1.Reverse().Select((c1, i) => new { c1 = c1 - '0', c2 = str2[str2.Length - i - 1] - '0' });

OTHER TIPS

My other answer is less useful than it could be, because the Enumerable.Zip function was added in version 4.

So, here's how to roll your own:

public static class EnumerableExtensions
{
    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
                                           IEnumerable<TFirst> first,
                                           IEnumerable<TSecond> second,
                                           Func<TFirst, TSecond, TResult> resultSelector)
    {
        using(var firstEnum = first.GetEnumerator())
        using(var secondEnum = second.GetEnumerator())
        {
            while(firstEnum.MoveNext() && secondEnum.MoveNext())
            {
                yield return resultSelector(firstEnum.Current, secondEnum.Current);
            }
        }
    }
}

Use Enumerable.Zip. Your first example can be rewritten from:

str2 = "91";
str1 = "19";
var testQuery = from c1 in str1
                from c2 in str2
                select new {c1, c2};
foreach (var enumerable in testQuery)
{
    Console.WriteLine(enumerable.c1 + " | " + enumerable.c2);
}

to

str2 = "91";
str1 = "19";
var strings = Enumerable.Zip(c1, c2, (a, b) => a + " | " + b);
foreach (var str in strings)
{
    Console.WriteLine(str);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top