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

Viewed 3182

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()) ;
2 Answers

You need Wheres 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();
Related