Single()严格返回一个元素项。如果返回的元素集合为空,或是返回的元素集合多于一个,Single()就会抛出异常。当程序需要严格要求返回一个元素时,不妨尝试用用Single()。
举例说明:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person() { }
public Person(string f, string l) { FirstName = f; LastName = l; }
}
...
var somePeople = new List<Person>
{
new Person { FirstName = "Bill", LastName = "Gates"},
new Person { FirstName = "Bill", LastName = "Wagner"},
new Person { FirstName = "Bill", LastName = "Johnson"}
};
var answer = from p in somePeople
where p.FirstName == "John"
select p;
// The following code throw an exception
// var answer2 = (from p in somePeople
// where p.FirstName == "John"
// select p).Single();
版权声明:本文为jianhui_wang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。