LINQ的代码,以选择一个项目 [英] Linq code to select one item

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

问题描述

我发现自己写了很多这样的代码来选择匹配

I find myself writing a lot of code like this to select one item that matches

var item = (from x in Items where x.Id == 123 select x).First();

是否有这样做的更清洁的方式或者是这个简明的我要得到什么?

Is there a cleaner way of doing it or is this as concise as I'm going to get?

编辑:如果使用LINQ的语法更清洁的方式说。我已经知道了lambda语法和它的开始看起来像这其实是唯一的出路。我确实得到了一些有用的信息了,所以感谢大家谁回答。

Should have said "Cleaner way using linq syntax". I was already aware of the lambda syntax and it's starting to look like this is actually the only way. I did get some useful info though, so thanks to everyone who replied.

推荐答案

要看你有多喜欢LINQ查询语法,你可以直接使用扩展方法,如:

Depends how much you like the linq query syntax, you can use the extension methods directly like:

var item = Items.First(i => i.Id == 123);



如果你不想抛出一个错误,如果列表为空,则使用 FirstOrDefault 返回为元素​​类型的默认值(对于引用类型):

And if you don't want to throw an error if the list is empty, use FirstOrDefault which returns the default value for the element type (null for reference types):

var item = Items.FirstOrDefault(i => i.Id == 123);

if (item != null)
{
    // found it
}

单()的SingleOrDefault()也可以用,但如果你是从数据库或一些已经保证唯一性我不会理会,因为它有扫描列表,查看是否有任何重复,并抛出阅读。 第一() FirstOrDefault()停在第一场比赛,所以他们更有效率。

Single() and SingleOrDefault() can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First() and FirstOrDefault() stop on the first match, so they are more efficient.

第一()单()家庭,这里的地方,他们抛出:

Of the First() and Single() family, here's where they throw:


  • 第一() - 将引发空的/没有找到,不扔如果重复

  • FirstOrDefault() - 返回默认是空的/没有找到,不投,如果重复

  • 单() - 将引发空的/没有找到,如果存在重复抛出

  • 的SingleOrDefault() - 返回默认是空的/没有找到,将引发存在重复

  • First() - throws if empty/not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty/not found, does not throw if duplicate
  • Single() - throws if empty/not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

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

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