序列包含多个元素-SingleOrDefault没有帮助 [英] Sequence contains more than one element - SingleOrDefault not helping
问题描述
我在下面的行中,但仍然出现异常"序列包含多个元素"
I have the line below but still get an exception "Sequence contains more than one element"
Details rd = this.db.Details.SingleOrDefault(x => x.TId == Id && x.TypeId == TypeId);
我希望SingleOrDefault可以避免该异常.
I was hoping that SingleOrDefault would avoid the exception.
推荐答案
SingleOrDefault
返回 SINGLE 元素;如果未找到任何元素,则返回null.如果在您的Enumerable中找到2个元素,那么它将引发您所看到的异常.就像Highlander ...和Single一样-只能有一个.
SingleOrDefault
returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing. Just like Highlander... with Single - there can be only one.
FirstOrDefault
返回找到的 FIRST 元素;如果未找到任何元素,则返回null.因此,如果有2个元素与您的谓词匹配,则第二个元素将被忽略.
FirstOrDefault
returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored.
假设您不在乎是否有多个匹配项,并且只希望第一个匹配项;如果找不到匹配项,则为null ...那么您可能想要以下内容...
Assuming you don't care if there are multiple matches and you only want the first one or null if no match is found... then you probably want the following...
Details rd = this.db.Details
.FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId);
请注意,这两种方法仅返回一个元素,它们在找到匹配项后的区别仅在于它们的作用不同. First
停止寻找该点并返回找到的内容,Single
继续检查列表的其余部分以确保不再有匹配项. OrDefault
部分确定在找不到匹配项的情况下返回的内容.如果找不到值,则SingleOrDefault
或FirstOrDefault
返回null,但是如果您仅使用Single
或First
,则它必须找到一个匹配项,否则将引发异常.
Note that both of these methods only return one element they only differ in what they do after they find a match. First
stops looking at that point and returns what it found, Single
keeps checking the rest of the list to make sure there are no more matches. The OrDefault
part determines what it returns if no match is found. SingleOrDefault
or FirstOrDefault
returns null if no value is found but if you just use Single
or First
then it MUST find one match or it will throw an exception.
好点,史蒂夫
由于First
返回第一个元素,因此您可能需要使用OrderBy
来确保所需的元素确实是第一个.例如...假设您的对象具有UpdateDate属性,并且您希望该对象具有最新的UpdateDate ...
Good point Steve
Since First
returns the first element you may need to use an OrderBy
in order to make sure the element you want is indeed first. For instance... suppose your object had an UpdateDate property and you wanted the object with the most recent UpdateDate...
Details rd = this.db.Details
.OrderByDescending(x => x.UpdateDate)
.FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId);
这篇关于序列包含多个元素-SingleOrDefault没有帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!