LINQ Single()异常,包含0个或多个项目 [英] LINQ Single() Exception for 0 or multiple items

查看:187
本文介绍了LINQ Single()异常,包含0个或多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些IEnumberable物品收藏.我使用.Single()在集合中查找特定对象.

I have some IEnumberable collection of items. I use .Single() to find a specific object in the collection.

我选择使用Single(),因为应该只有一个特定的项目.但是,如果不存在,那么我需要创建它并将其添加到集合中.

I choose to use Single() because there should only ever be one specific item. However, if one doesn't exist, then I need to create it and add it to the collection.

我的问题是,如果没有与谓词匹配的项目或有多个项目,则Single()会引发相同的错误.我的想法是将Single()调用放入尝试中并捕获异常,添加项目,然后继续.但是,由于两种情况都抛出了InvalidOperationException,我该如何判断是否是由于没有项目或有多个项目?

My problem is that Single() throws the same error if there is no item matching the predicate or if there are multiple items. My idea was to put the Single() call inside of a try and catch the exception, add the item, and then continue. However, since both scenarios throw the InvalidOperationException, how can I tell if its due to no items or multiple items?

我知道我可以使用First(),但这并不能强行提出只应该有一个的想法(无需做额外的工作).

I know I can use First() but that doesn't enforce the idea that there should be only one (without doing extra work).

我还可以在Single()调用之前使用Count(),但这似乎破坏了Single()

I could also use Count() before the Single() call, but that just seems to undermine the point of Single()

推荐答案

您想要的是SingleOrDefault()

或默认值"实际上意味着它返回null(对于引用类型)或任何非引用类型的默认值.您需要更新一个对象才能代替它.

The "or default" actually means it returns null (for reference types) or whatever the default would be for a non-reference type. You'll need to new-up an object to take its place.

这篇关于LINQ Single()异常,包含0个或多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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