Search code examples
c#listlambdamany-to-manyone-to-many

Convert List<string> containing many-to-many relationship items into one-to-many relationship


I have a List that contains strings which are delimited by a ' ' The list serves to function as a list of many to many relationships:

Category1 Item1
Category1 Item2
Category1 Item3
Category2 Item1 
Category2 Item2 
Category2 Item3
Category2 Item4
Category2 Item5
Category3 Item1 

I need to convert this list into one which has a one to many relationship order, with the items separated by a ';' example:

Category1 Item1;Item2;Item3
Category2 Item1;Item2;Item3;Item4;Item5
Category3 Item1

I have multiple foreach loops right now. I would love to share with you the many methods I've tried but it's truly a mess. However, something tells me there might be a Lambda technique to achieve this. Can anyone point me in the right direction? Thanks


Solution

  • var items = new List<string> {
       "Category1 Item1",
       "Category1 Item2",
       "Category1 Item3",
       "Category2 Item1",
       "Category2 Item2",
       "Category2 Item3",
       "Category2 Item4",
       "Category2 Item5",
       "Category3 Item1"
    };
    
    var result = items.Select(x => x.Split(' '))
                      .Select(x => new {
                         Category = x[0],
                         Item = x[1]
                      })
                      .GroupBy(x => x.Category, y => y.Item, (k, e) => string.Join(";", e))
                      .ToList();
    
    Console.ReadLine();