Domanda

just got curious if this LINQ Statement:

  string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  var shortDigits = digits.Where((digit, index) => digit.Length < index);

is convertible to this style of LINQ:

  var shortDigits  = from d in digits
                     ..........

If yes, can you please show me how...

È stato utile?

Soluzione

The problem you're having is that the overload of Where that you're using isn't supported in the fluent query syntax.

You can however get around this by performing a select first and projecting the index into your results like so:

var digitsWithIndex = digits.Select((d, i) => new { Digit = d, Index = i });

You can then consume the index in the fluent query syntax:

var query = from d in digitsWithIndex
            where d.Digit.Length < d.Index
            //just select the digit, we don't need the index any more
            select d.Digit;

This yields the results "five", "six", "seven", "eight", "nine".

I think in this situation I'd recommend sticking with using lambda syntax though, but that's my personal preference.

Here's the full code that I knocked up in LinqPad:

var digits = new []
{
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
};

var digitsWithIndex = digits.Select((d, i) => new { Digit = d, Index = i });

var query = from d in digitsWithIndex
            where d.Digit.Length < d.Index
            //just select the digit, we don't need the index any more
            select d.Digit;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top