user7393522
user7393522

Reputation: 41

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

Upvotes: 3

Views: 4213

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460158

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.

Upvotes: 4

GPW
GPW

Reputation: 2626

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

Upvotes: 0

Related Questions