[英]Extract specific object properties from a list of objects into a list
我有以下接口列表:
List<IInterfaces> instantiatedInterfaces;
IInterfaces
具有以下屬性:
List<StandardPort> ListOfPorts { get; }
UInt16 NumberOfPorts { get; }
StandardPort
具有屬性:
public Uint16 Side { get; set; }
現在,假設instantiatedInterfaces
已正確填充,如何將instantiatedInterfaces
接口包含的所有接口的ListOfPorts
所有端口(用於特定Side
)提取到List<StandardPort>
我嘗試過的方法(不起作用-返回一個空列表):
List<StandardPort> foundPorts = instantiatedInterfaces.Select(i => i.ListOfPorts.Where(p => p.side == Left)) as List<StandardPort>;
您正在尋找SelectMany()
List<StandardPort> result = instantiatedInterfaces
.SelectMany(w => w.ListOfPorts)
.Where(p => p.side == Left)
.ToList();
List<StandardPort> ports = instantiatedInterfaces .SelectMany(intf => intf.ListOfPorts) .Where(port => port.side == Left) .ToList();
您可以使用Enumerable.SelectMany
將“列表列表”展平為單個列表:
var allPorts = instantiatedInterfaces.SelectMany(iface => iface.ListOfPorts);
然后,您可以使用Enumerable.Where
過濾此列表:
var foundPorts = allPorts.Where(port => port.Side == Left).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.