how to determine logic of a linq where clause?

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
 
M

Martin Honnen

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top