Your final output example seems to be just duplicating the information in a collection grouped by PartNumber. Here is an example of how to group your list.Each item in the list is split into a 2 element array from which a collection of value tuples of type (string id, string part)
is constructed. That collection is grouped by id
. The nested foreach
loops just iterate over each group.
List<string> parts = new List<string> { "ABC 1", "ABC 2", "ABC 3", "XYZ 4", "XYZ 5" };
var grps= parts.Select(s => s.Split(' ')).Select(a => (id:a[0],part: a[1])).GroupBy(v=>v.id);
foreach (var group in grps)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var p in group)
{
Console.WriteLine(" {0}", p.part);
}
}