从列表中选择一个项目 [英] Select single item from a list

查看:64
本文介绍了从列表中选择一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表中可能不存在某项,则使用LINQ从列表中选择单个项的最佳方法是什么?

Using LINQ what is the best way to select a single item from a list if the item may not exists in the list?

我想出了两个解决方案,我都不喜欢.我使用where子句选择项目列表(我知道只会是一个),然后我可以检查计数并在该列表上进行单次调用(如果count为1的话),另一种选择是使用foreach并只拿到物品后休息.

I have come up with two solutions, neither of which I like. I use a where clause to select the list of items (which I know will only be one), I can then check the count and make a Single call on this list if count is one, the other choice is to use a foreach and just break after getting the item.

这两种方法都不是好方法,有没有更好的方法?

Neither of these seem like a good approach, is there a better way?

推荐答案

您可以使用IEnumerable.First()IEnumerable.FirstOrDefault().

区别在于,如果未找到任何元素(或者如果使用条件,则没有元素与条件匹配),则会抛出First(). FirstOrDefault()将返回default(T)(如果是引用类型,则返回null).

The difference is that First() will throw if no element is found (or if no element matches the conditions, if you use the conditions). FirstOrDefault() will return default(T) (null if it's a reference type).

这篇关于从列表中选择一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆