Linq返回特定类型 [英] Linq returning specific type
本文介绍了Linq返回特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Linq查询中返回特定类型?我知道您可以使用ToList()返回特定对象的列表,但是如何返回非列表?
How do you return a specific type in a Linq query? I know you can use ToList() to return a list of specific objects but how do you return a non list?
MyObj x = from x in list where x.id == 99 select x;
推荐答案
MyObj x = list.FirstOrDefault(i=>i.id == 99);
您可以使用
替代IEnumerable
方法来返回单个项目:
Alternative IEnumerable
methods you can use to return a single item:
-
list.Single(i=>i.id == 99)
:如果未找到匹配项或找到多个匹配项,则会引发异常. -
list.SingleOrDefault(i=>i.id == 99)
:如果未找到匹配项,则返回null;如果发现多个匹配项,则引发异常. -
list.First(i=>i.id == 99)
:如果未找到匹配项,则引发异常.如果找到多个匹配项,则返回列表中的第一项. -
list.FirstOrDefault(i=>i.id == 99)
:如果未找到匹配项,则返回null.如果找到多个匹配项,则返回列表中的第一项.
list.Single(i=>i.id == 99)
: throws an exception if no matches are found or multiple matches are found.list.SingleOrDefault(i=>i.id == 99)
: returns null if no matches are found, throws an exception if multiple matches are found.list.First(i=>i.id == 99)
: throws an exception if no matches are found. If multiple matches are found, returns the first item in the list.list.FirstOrDefault(i=>i.id == 99)
: returns null if no matches are found. If multiple matches are found, returns the first item in the list.
这篇关于Linq返回特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文