问题描述
我有此示例代码:
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); }
是否有一种方式通过使用LINQ表达式生成相同的输出 ?
推荐答案
我知道您仅指var shortDigits = digits.Where((digit, index) => digit.Length < index);我必须努力思考为什么您要创建这样的怪物,如果您指的是仅使用LINQ
生成整个输出您可以执行以下操作以获取相同的输出:
int i = 0; var shortDigits = from d in digits where d.Length < i++ select d;
其他推荐答案
一个长1班轮
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())));
使用一些自定义扩展方法可以简化代码.例如, todelimeteredstring() a>
其他推荐答案
您不能用Linq做到这一点(嗯,如果您滥用它可以,但我们不想去那里),因为Linq应该没有副作用,并且打印数字绝对是副作用(从某种意义上说,它不会影响数字本身).
但是,您可以使用List.ForEach方法足够近:
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));
问题描述
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:"); foreach (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));