-1

I have a list that contains name/value pairs

Class looks like this:

string Name { get; set; }
string Value { get; set; }

What I need to do is concatenate all of the values that have the same name into a new list where the class looks like this:

string Name { get; set; }
list<string> Values { get; set; }
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • Think you might want to look at this: [ToLookup()](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolookup?view=netframework-4.7.2). – John Wu Jan 31 '19 at 23:09
  • 1
    `var combined = nvpList.GroupBy(nvp => nvp.Name).Select(group => new NameValueClass {Name = group.Key, Values = group.SelectMany(nvp => nvp.Values).Distinct().ToList()});` – Rufus L Jan 31 '19 at 23:26
  • Rufus you saved the day. This is EXACTLY what I was looking for. Thank you! – Scott Boyte Feb 01 '19 at 00:40

1 Answers1

1

You can use LINQ GroupBy method:

var result = yourList.GroupBy(x => x.Name, x => x.Value, 
    (k, g) => new YouSecondClass { Name = key, Values = g.ToList() });
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125