LINQ:何时使用 SingleOrDefault 与 FirstOrDefault() 与过滤条件

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria(LINQ:何时使用 SingleOrDefault 与 FirstOrDefault() 与过滤条件)
本文介绍了LINQ:何时使用 SingleOrDefault 与 FirstOrDefault() 与过滤条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑 IEnumerable 扩展方法 SingleOrDefault()FirstOrDefault()

Consider the IEnumerable extension methods SingleOrDefault() and FirstOrDefault()

MSDN 文档 SingleOrDefault:

返回序列的唯一元素,如果序列为空,则返回默认值;如果序列中有多个元素,此方法将引发异常.

Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

FirstOrDefault 来自 MSDN (大概在使用 OrderBy()OrderByDescending() 或根本不使用时),

whereas FirstOrDefault from MSDN (presumably when using an OrderBy() or OrderByDescending() or none at all),

返回序列的第一个元素

考虑一些示例查询,并不总是很清楚何时使用这两种方法:

Consider a handful of example queries, it's not always clear when to use these two methods:

var someCust = db.Customers
.SingleOrDefault(c=>c.ID == 5); //unlikely(?) to be more than one, but technically COULD BE

var bobbyCust = db.Customers
.FirstOrDefault(c=>c.FirstName == "Bobby"); //clearly could be one or many, so use First?

var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or does it matter?

问题

在决定在 LINQ 查询中使用 SingleOrDefault()FirstOrDefault() 时,您遵循或建议哪些约定?

What conventions do you follow or suggest when deciding to use SingleOrDefault() and FirstOrDefault() in your LINQ queries?

推荐答案

每当你使用 SingleOrDefault,您清楚地声明该查询最多应该产生一个 single 结果.另一方面,当 FirstOrDefault 使用,查询可以返回任意数量的结果,但你声明你只想要第一个.

Whenever you use SingleOrDefault, you clearly state that the query should result in at most a single result. On the other hand, when FirstOrDefault is used, the query can return any amount of results but you state that you only want the first one.

我个人发现语义非常不同,根据预期结果使用适当的语义可以提高可读性.

I personally find the semantics very different and using the appropriate one, depending on the expected results, improves readability.

这篇关于LINQ:何时使用 SingleOrDefault 与 FirstOrDefault() 与过滤条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)