Home > Software engineering >  C#: Combine two elements of the SAME list (no duplicates)
C#: Combine two elements of the SAME list (no duplicates)

Time:10-25

I have a list of objects.

These objects have among other elements one string called "reference". The list might look like this:

|reference| description |
|123      | this should |
|124      | sth         |
|125      | sth         |
|123      | be one      |

I want to combine WITHIN this list all elements with the same reference. Result should be:

|reference| description       |
|123      | this should be one|
|124      | sth               |
|125      | sth               |

into a new list. So far I could only find solutions on how to group or how to combine two lists. Any ideas?

CodePudding user response:

You should group them according to reference field and concatenate the descriptions.

Something like this should work

var results = list
              .GroupBy(i => i.Reference)
              .Select(g => 
                  (Reference: g.Key, 
                   Description: string.Join(" ", g
                       .Select(i => i.Description)));

CodePudding user response:

Depending on your needs you can use an anonymous object or generate a new list of the type of yourclass...

void Main()
{
    var list = new List<YourClass>()
    {
        new YourClass{Reference = 123, Description = "this should"},
        new YourClass{Reference = 124, Description = "sth"},
        new YourClass{Reference = 125, Description = "sth"},
        new YourClass{Reference = 123, Description = "be one"},
    };
    
    var combined = list
        .GroupBy(item => item.Reference)
        .Select(group => new YourClass
        {
            Reference = group.Key, 
            Description = string.Join(" ", group.Select(element => element.Description))
        });
        
    Console.WriteLine(combined);
}

class YourClass
{
    public int Reference {get;set;}
    public string Description {get;set;}
}

enter image description here

  • Related