.net LINQ 中的 DefaultIfEmpty
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8854181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DefaultIfEmpty in LINQ
提问by Nate Pet
Can somebody explain how DefaultIfEmpty()can be used in LINQ. I have ready some material but still need something solid to see what the use of it is.
有人可以解释如何DefaultIfEmpty()在LINQ 中使用。我已经准备好了一些材料,但仍然需要一些扎实的东西来看看它的用途。
回答by vc 74
It basically returns a collection with a single element in case the source collection is empty.
如果源集合为空,它基本上返回一个包含单个元素的集合。
var numbers = new int[] {1, 2, 3};
var aNumber = numbers.First();
returns 1
返回 1
but
但
var numbers = new int[];
var aNumber = numbers.DefaultIfEmpty(12).Single();
returns 12 as the collection is empty
当集合为空时返回 12
回答by Nigel Shaw
The difference is the DefaultIfEmpty returns a collection of objects while FirstOrDefault returns an object. If there were no results found DefaultIfEmpty still returns an Enumerable with a single item that has its default value, whereas FirstOrDefault returns T itself.
区别在于 DefaultIfEmpty 返回一个对象集合,而 FirstOrDefault 返回一个对象。如果没有找到结果, DefaultIfEmpty 仍然返回一个 Enumerable ,其中包含一个具有默认值的项目,而 FirstOrDefault 返回 T 本身。
You use DefaultIfEmpty if you need always need a collection result, for instance to create outer joins. You use FirstOrDefault if you always need an object (not a collection) result, for instance if you want to get the first item (or only item) when searching for something like an ID or unique email, and want to return the default empty item if the item you were searching for was not found.
如果您需要始终需要一个集合结果,例如创建外部联接,您可以使用 DefaultIfEmpty。如果您总是需要一个对象(而不是集合)结果,例如,如果您想在搜索 ID 或唯一电子邮件之类的内容时获取第一个项目(或唯一项目),并且想要返回默认的空项目,则可以使用 FirstOrDefault如果未找到您要搜索的项目。

