Merge duplicates in List<T>

I have a List as shown below.

var boxes= new List<Box>(){
new Box(){ Id=1, Name="A1", SrNo="A11"},
new Box(){ Id=2, Name="A1", SrNo="A22"},
new Box(){ Id=3, Name="B1", SrNo="B11"},
new Box(){ Id=4, Name="B1", SrNo="B22"},
new Box(){ Id=5, Name="C1", SrNo="C11"},
new Box(){ Id=6, Name="D1", SrNo="D11"}
}

I want to clean the list by merging duplicates by Name so that output looks like this.

var boxes = {
        new Box(){ Id=1, Name="A1", SrNo="A11, A22"},
        new Box(){ Id=3, Name="B1", SrNo="B11, B22"},
        new Box(){ Id=5, Name="C1", SrNo="C11"},
        new Box(){ Id=6, Name="D1", SrNo="D11"}
        }

I understand that I need to do GroupBy but how do I update SrNo so that it appends values from duplicates & remove duplicates rows as well from list ?



Read more here: https://stackoverflow.com/questions/64398827/merge-duplicates-in-listt

Content Attribution

This content was originally published by HelloWorld2020 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: