Search code examples
c#linq

How can I list classes with similar IDs in a list with Linq?


I have NodeViewModel class. There is ID variable in NodeViewModel class. It can be two classes but with the same ID variable. IDs are not sequential numbers. Example ID; 010105.

I have a list containing my NodeViewModels as follows;

List<NodeViewModel> nodes = new List<NodeViewModel>((IEnumerable<NodeViewModel>)diagram.Nodes);

It is necessary to export the information in the content of two matching classes by combining them. Therefore I created a class called IdNodeInteractionModel. I want to collect matching NodeViewModels in a List.

public class IdNodeInteractionModel
{
    public int ID;
    public NodeViewModel firstNode;
    public NodeViewModel secondNode;
}

I can match similar ids with multiple foreach loops. But I am using similar loops. There are if else queries and all of them reduce the readability of the code. How can I make practical readability with Linq?

I would be glad if you help.


Solution

  • It can be two classes but with the same ID variable

    Sounds like you are looking for GroupBy/ToLookup. For example:

    List<NodeViewModel> nodes = new List<NodeViewModel>();
    var result = nodes
        .GroupBy(n => n.ID)
        .Select(g =>
        {
            var pair = g.Take(2).ToArray(); // ignore the rest if we have more then 2
            return new IdNodeInteractionModel
            {
                ID = g.Key,
                FirstNode = pair[0],
                SecondNode = pair.Length > 1 ? pair[1] : null
            };
        })
        .ToList();