多重枚举和使用Any() [英] Multiple enumeration and use of Any()
本文介绍了多重枚举和使用Any()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我需要执行以下操作时,我试图弄清楚LINQ的正确约定是什么
I'm trying to figure out what would be the proper convention for LINQ when I need to do something like the following
- 如果有项目,请逐行打印它们
- 如果没有项目,请打印
没有项目"
我想去做的方式就像
if (items.Any())
{
foreach (string item in items)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("No items");
}
但是,从技术上讲,这将违反多重枚举的原理.一种不违反规定的方法是
However, that would technically violate the principle of multiple enumeration. A way to not violate that would be
bool any = false;
foreach (string item in items)
{
any = true;
Console.WriteLine(item);
}
if (!any)
{
Console.WriteLine("No items");
}
但很明显,这不太优雅.
but clearly, that is less elegant.
推荐答案
既然我们在谈论LINQ,那么一个非常LINQ的解决方案又如何呢?
Since we are talking LINQ, how about a very LINQ solution?
foreach (var item in items.DefaultIfEmpty("No items"))
Console.WriteLine(item);
这篇关于多重枚举和使用Any()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文