本文介绍了多重枚举和使用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()
发布评论