Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading