C# 如何使用Where扩展函数选择N个列表中的元素?

C# 如何使用Where扩展函数选择N个列表中的元素?,c#,extension-methods,ienumerable,C#,Extension Methods,Ienumerable,假设我有一个类AddressType,其定义如下: public class AddressType { public int AddressTypeId { get; set; } public string Description { get; set; } } 代码中有一个列表对象,如何选择具有已知AddressTypeId属性的AddressType对象 我从未使用过列表。Where扩展函数 谢谢 IEnumerable addressList=。。。 IEnumera

假设我有一个类AddressType,其定义如下:

public class AddressType {
    public int AddressTypeId { get; set; }
    public string Description { get; set; }
}
代码中有一个列表对象,如何选择具有已知AddressTypeId属性的AddressType对象

我从未使用过列表。Where扩展函数

谢谢

IEnumerable addressList=。。。
IEnumerable<AddressType> addressList = ...
IEnumerable<AddressType> addresses = addressList.Where(a => a.AddressTypeId == 5);
IEnumerable addresses=addressList,其中(a=>a.AddressTypeId==5);
或:

IEnumerable地址=
从地址列表中的地址
其中address.AddressTypeId==5
选择地址;

通过使用
Where
,您可以获得列表中具有特定ID的所有
AddressType
对象:

IEnumerable<AddressType> addressTypes = list.Where(a => a.AddressTypeId == 123);
这将在列表中找到ID为123的第一个
AddressType
,如果找不到则抛出异常

另一种变体是使用
FirstOrDefault

AddressType addressType = list.FirstOrDefault(a => a.AddressTypeId == 123);
如果不存在具有请求的ID的
AddressType
,它将返回
null

如果要确保列表中存在一个具有所需ID的
AddressType
,可以使用
Single

AddressType addressType = list.Single(a => a.AddressTypeId == 123);
这将引发异常,除非列表中正好有一个ID为123的
AddressType
Single
必须枚举整个列表,使其比
First

AddressType addressType = list.FirstOrDefault(a => a.AddressTypeId == 123);
AddressType addressType = list.Single(a => a.AddressTypeId == 123);