简体   繁体   English

SingleOrDefault()引发异常序列包含多个匹配元素

[英]SingleOrDefault() Throw exception Sequence contains more than one matching element

i have dictionary and there are few element has been stored like 我有字典,几乎没有存储任何元素,例如

    Dictionary<string, string> dService = new Dictionary<string, string>();
    dService.Add("UPS Express Plus", "001");
    dService.Add("UPS Express Plus", "054");
    dService.Add("UPS Express", "007");
    dService.Add("UPS Express Saver", "065");
    dService.Add("UPS Expedited", "008");
    dService.Add("UPS Express Plus", "001");

this way i am trying to get key based on value 这样我试图基于价值来获取钥匙

dService.SingleOrDefault(x => x.Value == ("001")).Key

this code is throwing error. 此代码引发错误。 i search google and got solution that people saying not to use SingleOrDefault() rather use FirstOrDefault() 我搜索谷歌,并得到解决方案,人们说不要使用SingleOrDefault()而是使用FirstOrDefault()

but i got no good explanation why & when SingleOrDefault() throw error ? 但是我没有很好的解释为什么&当SingleOrDefault()抛出错误? should i presume that dictionary store multiple value that is why SingleOrDefault() will not work? 我应该假定该字典存储多个值,这就是为什么SingleOrDefault()无法正常工作的原因?

looking for explanation when why & when SingleOrDefault() throw error....please guide me sample situation. 寻找解释何时以及何时SingleOrDefault()引发错误...。请指导我示例情况。 thanks 谢谢

First, your sample-data above does not throw since it doesn't contain multiple equal values which are "001" . 首先,上面的样本数据不会抛出,因为它不包含多个等于"001"相等值。 It would if you'd add two values with Value="001" . 如果您要添加两个带有Value="001"

If you enumerate a dictionary you get an IEnumerable<KeyValuePair<TKey, TValue>> . 如果枚举字典,则会得到IEnumerable<KeyValuePair<TKey, TValue>> You are asking for the first and only value in the dictionary which is "001" . 您正在要求字典中的第一个也是唯一的值"001" Of course a dictionary can contain multiple equal Values (but only unique keys). 当然,字典可以包含多个相等的 (但只能是唯一的键)。

So you could use FirstOrDefault instead which doesn't throw on multiple results. 因此,您可以改用FirstOrDefault ,它不会引发多个结果。 Another way is to find all with Where , then Select the key: 另一种方法是使用Where来查找所有内容,然后Select键:

IEnumerable<string> all001ValKeys = dService
    .Where(kv => kv.Value == "001")
    .Select(kv => kv.Key);

SingleOrdefault (or Single ) is handy if you want to ensure a business rule like: 如果您想确保像以下这样的业务规则,则可以使用SingleOrdefault (或Single ):

var record = someTable.Single(obj => obj.ID == 123); // ID must be unique

This makes your code more readable and also follows the "failing fast"-rule. 这使您的代码更具可读性,并且遵循“快速失败”规则。

FirstOrDefault is used if you want first element in list , if no data in list , it will return you default value (which is null) else it will return you first element of list. 如果您想要列表中的第一个元素,则使用FirstOrDefault;如果列表中没有数据,它将返回您的默认值(为null),否则将返回您列表的第一个元素。

SingleOrDefault is used when you are sure only one element in list , if it is not in list , it will return default (which is null), but if it has more then single value , it will throw you exectption. 当您确定list中只有一个元素时,将使用SingleOrDefault,如果它不在list中,它将返回default(为null),但是如果它具有单个值以上,则将抛出异常。

I hope this explanation is use full for you. 我希望这个解释对您有用。

Note that FirstOrDefault on an Dictionary returns a KeyValuePair containing the default values for the defined Key and Value types. 请注意, FirstOrDefault上的FirstOrDefault返回一个KeyValuePair,其中包含已定义键和值类型的默认值。 Since you're using string as Key and Value, both will be null. 由于您使用字符串作为键和值,因此两者均为空。 So the result of your LINQ expression will be null and working with the key may result in a NullReferenceException later in your code. 因此,LINQ表达式的结果将为null,并且使用该键可能会在稍后的代码中导致NullReferenceException。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SingleOrDefault:仅捕获“序列包含多个元素” InvalidOperationException - SingleOrDefault: Catch just “Sequence contains more than one element” InvalidOperationException InvalidOperationException:序列包含多个元素-SingleOrDefault() - InvalidOperationException: Sequence contains more than one element - SingleOrDefault() 序列包含多个元素 - SingleOrDefault 没有帮助 - Sequence contains more than one element - SingleOrDefault not helping Sequence包含多个匹配元素 - Sequence contains more than one matching element NHibernate 3.1 NHibernate.Linq.NhRelinqQueryParser异常“序列包含多个匹配元素” - NHibernate 3.1 NHibernate.Linq.NhRelinqQueryParser exception “Sequence contains more than one matching element” Include()ThenInclude()在Table Per Hierarchy策略中抛出“Sequence包含多个匹配元素”异常 - Include() ThenInclude() throws “Sequence contains more than one matching element” exception in Table Per Hierarchy strategy 实体框架迁移:序列包含多个匹配元素 - Entity Framework Migration: Sequence contains more than one matching element 序列在批量插入上包含多个匹配元素 - sequence contains more than one matching element on Bulk insert Linq InvalidOperationException:序列包含多个匹配元素 - Linq InvalidOperationException: Sequence contains more than one matching element FirstOrDefault抛出'Sequence包含多个匹配元素' - FirstOrDefault throws 'Sequence contains more than one matching element'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM