开发者

C# LINQ expression question

I have this sample code:

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:");
fo开发者_运维问答reach (var d in shortDigits)
{
    Console.WriteLine("The word {0} is shorter than its value.", d);
}

Is there a way generating same output only by using LINQ expressions?


I understand you are referring only to var shortDigits = digits.Where((digit, index) => digit.Length < index); I would have to think hard why you'd want to create such a monster if you are referring to generating the whole output with only LINQ

You could do the following to get the same output:

int i = 0;
var shortDigits = from d in digits
                  where d.Length < i++
                  select d;


One long 1 liner

Console.WriteLine(
  string.Format("Short digits: \r\n{0}",
    string.Join(Environment.NewLine, 
        digits.Where((digit, index) => digit.Length < index)
              .Select(digit => 
                string.Format("The word {0} is shorter than its value.", digit))
                      .ToArray())));

Using some custom extension methods may ease the code. For example ToDelimeteredString()


You cannot do this with LINQ (well, you can if you abuse it, but we don't want to go there) because LINQ is supposed to be free of side effects, and printing the numbers is most definitely a side effect (in the sense that it does not affect the numbers themselves).

However, you can get close enough with the List.ForEach method:

Console.WriteLine("Short digits:");

var shortDigits = digits.Where((digit, index) => digit.Length < index);
shortDigits.ToList().ForEach(d => 
    Console.WriteLine("The word {0} is shorter than its value.", d));


It is trivial to implement a Linq-like extension method that works like a foreach loop (see e.g. this question), but it has intentionally been left out of the Linq framework functions, because they are designed to be side-effect free. Therefore the way you are currently doing it is considered a better practice.


You can do something like that:

var output = digits.Where(
    (digit, index) => digit.Length < index).Select(d => 
      string.Format("The word {0} is shorter than its value.", d));

But at some point you still need a loop to display the results...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜