簡體   English   中英

從對象列表中提取特定的對象屬性到列表中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM