从对象列表中提取特定的对象属性到列表中

时间:2019-08-01 09:42:32

标签: c# object lambda properties

我有以下接口列表:

List<IInterfaces> instantiatedInterfaces;

IInterfaces具有以下属性:

List<StandardPort> ListOfPorts { get; }
UInt16 NumberOfPorts { get; }

StandardPort具有以下属性:

public Uint16 Side { get; set; }

现在,假设instantiatedInterfaces已正确填充,我如何才能将List<StandardPort>的所有端口(对于特定的ListOfPorts)提取到SideinstantiatedInterfaces

包含的接口

我尝试过的方法(不起作用-返回一个空列表):

List<StandardPort> foundPorts = instantiatedInterfaces.Select(i => i.ListOfPorts.Where(p => p.side == Left)) as List<StandardPort>;

3 个答案:

答案 0 :(得分:3)

您正在寻找SelectMany()

SHA Hash

答案 1 :(得分:2)

List<StandardPort> ports = instantiatedInterfaces
    .SelectMany(intf => intf.ListOfPorts)
    .Where(port => port.side == Left)
    .ToList();

答案 2 :(得分:2)

您可以使用Enumerable.SelectMany将“列表列表”展平为一个列表:

var allPorts = instantiatedInterfaces.SelectMany(iface => iface.ListOfPorts);

然后您可以使用Enumerable.Where过滤此列表:

var foundPorts = allPorts.Where(port => port.Side == Left).ToList();
相关问题