how to determine logic of a linq where clause?

  • Thread starter Thread starter Rich P
  • Start date Start date
R

Rich P

The following sample linq query (below) works fine. My problem is how I
would know to set up the indexed where clause for this sample:

var shortDigits = digits.Where((digit, index) => digit.Length < index);

isn't var like a variant? could be anything? digits[] is a string
array - given. I renamed the params in the Where clause, and it still
works:

var shortDigits = digits.Where((steve, puppy) => steve.Length < puppy);

The intellisense has fairly descent documenting, but is there formal
documentation on linq "where" clauses or the logic behind them? Or is
it just a matter of doing enough linq samples until you instinctively
start getting a feel for it?

------------------------------------------------------

This sample uses an indexed Where clause to print the name of each
number, from 0-9, where the length of the number's name is shorter than
its value. In this case, the code is passing a lambda expression which
is converted to the appropriate delegate type. The body of the lambda
expression tests whether the length of the string is less than its index
in the array.

public void Linq5()
{
string[] digits = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };

var shortDigits = digits.Where((digit, index) => digit.Length <
index);

Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine("The word {0} is shorter than its value.", d);
}
}


Rich
 
Rich said:
The following sample linq query (below) works fine. My problem is how I
would know to set up the indexed where clause for this sample:

var shortDigits = digits.Where((digit, index) => digit.Length < index);

isn't var like a variant? could be anything? digits[] is a string
array - given. I renamed the params in the Where clause, and it still
works:

var shortDigits = digits.Where((steve, puppy) => steve.Length < puppy);

As the argument to the Where function you are writing an anonymous
function where you name the parameters. The name of function parameters
can be freely choosen, whether you write a lambda expression or a method
makes no difference.

As for var being like a variant, no, it is not, the compiler infers the
type during compile time.
 
Back
Top