LINQ in Action - LINQ Book & News

Using the Select LINQ query operator with indexes

Yesterday, Fred asked me if I could help him to convert C# code to LINQ. The solution may not obvious to find unless you know LINQ well. I will reproduce here the solution I gave Fred. Whether the LINQ version of the code is easier to read than the original one is arguable. The purpose here is more to show LINQ's Select query operator in action.

Here is the original code:

int CountCorrectChars(string proposedValue, string correctValue)
  int correctCount = 0;
  for (int i = 0; i < proposedValue.Length && i < correctValue.Length; i++)
    if (proposedValue[i] == correctValue[i])
  return correctCount;

Here is the LINQ version that I suggested:

int CountCorrectChars(string proposedValue, string correctValue)
return correctValue
    .Select((testChar, index) => new { Character = testChar, Index = index })
    .Count(testChar => (testChar.Index < proposedValue.Length)
&& (testChar.Character == proposedValue[testChar.Index]));

As you can see, the LINQ version is not so easy to understand and is verbose. Of course, we could use shorter names, but that wouldn't change the complexity of the query. The LINQ version is not as good in terms of performance either... So, should we use LINQ or not? My point here is that LINQ is not a "one size fits all" solution. You should use it wisely and avoid complexifying code by choosing always to use LINQ.

What's interesting in this example, is also simply the use of Select with a two-parameter lambda expression. You may know the version of Select that takes a single-parameter lambda well, but its counterpart is less known (and used).

This is something that we cover in LINQ in Action in section 4.4.2. Here is what we write there, which gives another example of Select in action:

The Select and SelectMany operators can be used to retrieve the index of each element in a sequence. Let’s say we want to display the index of each book in our collection before we sort them in alphabetical order:

index=3         Title=All your base are belong to us
index=4         Title=Bonjour mon Amour
index=2         Title=C# on Rails
index=0         Title=Funny Stories
index=1         Title=LINQ rules

Here is how to use Select to achieve that:

Listing 4.15    Code-behind for the first ASP.NET page    (SelectIndex.csproj)
var books =
    .Select((book, index) => new { index, book.Title })
    .OrderBy(book => book.Title);

This time we can’t use the query expression syntax because the variant of the Select operator that provides the index has no equivalent in this syntax. Notice that this version of the Select method provides an index variable that we can use in our lambda expression (precision not in the book: its not the name "index" that is important. You can use another name if you want. What makes the difference is that the lambda expression takes two parameters). The compiler automatically determines which version of the Select operator we want to use just by looking at the presence or absence of the index parameter. Notice also that we call Select before OrderBy. This is important to get the indices before the books are sorted, not after.

...One more tool in your toolbox. Now, use it wisely.

Update: Mark Sowul suggests a simpler solution:

return correctValue.Where((testChar, index) => index < proposedValue.Length && testChar == proposedValue[index]).Count();
Somehow I missed that Where overload.


Published Monday, November 10, 2008 8:59 PM by Fabrice Marguerie



Derek said:

Adding a Select2 extension method for IEnumerable might help, here's how it shakes out in F#.

let CountCorrectChars proposedValue correctValue =

   Seq.map2 (=) proposedValue correctValue

   |> Seq.sum_by (fun good -> if good then 1 else 0)

November 10, 2008 3:23 PM

Fabrice Marguerie said:

Derek, I don't know F#, so I'll have to trust you on this :-)

November 11, 2008 1:06 AM
New Comments to this post are disabled