George George - 4 months ago 24
C# Question

Group string values

I have this code

var myBuilder = new StringBuilder();

foreach (var item in myList)
{
myBuilder.Append(item.Number).Append(" - ").Append(item.SecondNumber).Append(", ");
}

var text = myBuilder;


and using that I'm getting this text


AAA08 - BB08, AAA09 - BB09, AAA09 - BB10,


myList returns this:


{ Number = "AAA08", SecondNumber = "BB08" }

{ Number = "AAA09", SecondNumber = "BB09" }

{ Number = "AAA09", SecondNumber = "BB10" }


How can I concatenate it to string to display this:


AAA08 - BB08; AAA09 - BB09, BB10


I can do replace
,
to
;
but can't get how to group these
Number
to display only one and each
SecondNumber
right to him

Answer

You can do this with Linq and string.Join

var grouped = myList
    .GroupBy(x => x.Number)
    .Select(g => g.Key + " - " + string.Join(", ", g.Select(x => x.SecondNumber)))
var text = string.Join("; ", grouped);