Home > database >  How to combine objects in collection by equal property unsing LINQ?
How to combine objects in collection by equal property unsing LINQ?

Time:11-19

I have a collection of objects

ObservableCollection<ISettingNode> nodes = new ObservableCollection<ISettingNode>() {
      new Node("Node1", tabs1);
      new Node("Node1", tabs2);
      new Node("Node1", tabs3);
      new Node("Node2", tabs4);
      new Node("Node3", tabs5);
}

Could you please tell, how from this collection I can get a collection, where all object with equal Name will be united in one object. In my case I want to have first three elements of the collection as one which would be like Node("Node1", tabs) where tabs equal tabs1 tabs2 tabs3? So the result would be:

ObservableCollection<ISettingNode> nodes = new ObservableCollection<ISettingNode>() {
      new Node("Node1", tabs);
      new Node("Node2", tabs4);
      new Node("Node3", tabs5);
}

I know how to do it without Linq, but it has to much code. I would like to get it using Linq, but I can not understand how to write a query.

Nodes objects are represented by simple class:

  public class SettingNode : ISettingNode
    {
        public string Name { get; private set; }
        public IEnumerable<ISettingTab> Tabs { get; private set; }
    }

CodePudding user response:

You could GroupBy ISettingNode.Name, then project the groups back into an IEnumerable<ISettingNode> with the tabs grouped together.

Assuming the constructor for Node can take an IEnumerable<ISettingTab>...

IEnumerable<ISettingNode> groupedNodes = nodes
    .GroupBy(node => node.Name)
    .Select(grp => new Node(grp.Key, grp.SelectMany(grpNode => grpNode.Tabs)));

CodePudding user response:

You can use the GroupBy statement to an IEnumerable. You can then just pass that back into an Observable list:

nodes = new ObservableCollection<Node>(
           nodes
           .GroupBy(node => node.NodeName)
           .Select(node => new Node(node.Key, node.Select(x => x.Tab)))
        ); 
  • Related