C#中firstordefault()和singleordefault()之间的区别? [英] Difference between firstordefault() and singleordefault() in C#?

查看:433
本文介绍了C#中firstordefault()和singleordefault()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SingleOrdefault()和FirstOrdefault()之间



我尝试过:



Between SingleOrdefault() and FirstOrdefault()

What I have tried:

Difference between FirstorDefault() and SingleOrDefault() in C#?

推荐答案

首先或默认如果列表中没有任何内容,将返回默认类型,如果有一个或多个项目,则返回第一个项目。



单个或默认将返回默认类型在列表中,如果只有一个项目,列表中唯一的项目,如果列表中有多个项目,则会抛出异常。



所以区别在于,当有多个项时,FirstOrDefault会忽略,如果有多个项,SingleOrDefault会抛出异常。
First or default will return the type default if nothing is in the list, and the first item if there are one or more items.

Single or default will return the type default if nothing is in the list, the only item in the list if there is only one item, and will throw an exception if there is more than one item in the list.

So the difference is that FirstOrDefault ignores when there is more than one item, SingleOrDefault throws an exception if there is more than one item.


忽略我尝试过的内容这一事实并没有说你真的尝试了什么,这是一个相当有趣的问题要回答。让我们首先得出两种方法之间的相似之处:



它们都返回一个值。

该值将是值发现除非没有匹配,在这种情况下将返回默认值。

默认值将为null(对于可空类型)或非可空类型的默认值。



鉴于这组能力,他们为什么不同?



首先返回第一个匹配元素。换句话说,它停止扫描列表尽可能找到匹配

如果有一个元素,则返回匹配元素。换句话说,它继续扫描以确保只有一个匹配元素。
Ignoring the fact that the "What I have tried" section doesn't say that you actually tried anything, this is a fairly interesting question to answer. Let's get the similarities between the two methods out of the way first:

They both return one value.
That value will be the value found unless there is no match, in which case the default value will be returned.
The default value will either be null (for nullable types) or the default for a non-nullable type.

Given that set of abilities, why do they differ?

First returns the first matching element. In other words, it stops scanning the list AS SOON AS IT FINDS A MATCH.
Single returns the matching element ONLY if there is one element. In other words, it continues scanning to make sure there's only one matching element.


这篇关于C#中firstordefault()和singleordefault()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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