多重枚举和使用Any()

编程入门 行业动态 更新时间:2024-10-27 09:44:06
本文介绍了多重枚举和使用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()

本文发布于:2023-11-12 07:08:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!