简体   繁体   中英

Linq to select list of items from custom nested list of objects

I have created following object model for my application

public class Object
{
    public List<Node> Nodes { get; set; }
}

public class Node
{
    public InstrumentData InstrumentData { get; set; }        
}

public class InstrumentData
{       
    public List<MySysData> MySysDataList { get; set; }
}

public class MySysData
{       
    public string SystemName { get; set; }        
}

Now I have Object list of nodes. I want to select not null "SystemName" from Object node list to a string list
I have tried following query but still its not has expected.

 var test = Object.Nodes.ToList<Node>()
  .Select(x => x.InstrumentData?.MySysDataList.ToList<MySysData>()
  .Select(y => y.SystemName)
  .ToList()) ;

You need Where s and SelectMany :

List<string> sysNameList = Object.Nodes
   .Where(x => x.InstrumentData?.MySysDataList != null)
   .SelectMany(x => x.InstrumentData.MySysDataList
       .Select(y => y.SystemName)
       .Where(sName => sName != null))
   .ToList();

If you want to remove duplicates prepend Distict before the final ToList .

If you literally want just the system names, then because your internal select is returning a list (so the eventual output is a list of lists) you'll need to use SelectMany to 'flatten out' the list. As long as things are enumerable you also don't need to repeatedly use ToList() all the time. something like this ought to work I think:

var test = Object.Nodes
    .SelectMany(x => x.InstrumentData?.MySysDataList.Select(y => y.SystemName))
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM