0

I have a list that contains two properties, Sequence and Term.

termData <int,string> 

For each Sequence there can be multiple Terms.

Is there a way that I can combine the terms for each Sequence number such that it creates another list looking something like:

1438690 "weather; the elements; fair weather

enter image description here

Alan2
  • 23,493
  • 79
  • 256
  • 450

3 Answers3

3
var _result = termData.GroupBy(x => x.Sequence)
                .Select(x => new
                {
                    seq = x.Key,
                    term = x.Select(y => y.Term).ToList()
                });
Makarov2015
  • 139
  • 1
  • 6
2
var list = new List<termData>();
list.Add(new termData() { Sequence = 1438690, Terms = "weather" });
list.Add(new termData() { Sequence = 1438690, Terms = "the elements" });
list.Add(new termData() { Sequence = 9672410, Terms = "dogs" });
list.Add(new termData() { Sequence = 9672410, Terms = "cats" });

var result = list
    .GroupBy(t => t.Sequence, t => t.Terms)
    .Select(g => g.Key + ";" + String.Join(";", g));
foreach (var item in result)
{
    Console.WriteLine(item);
}

Output:

1438690;weather;the elements
9672410;dogs;cats
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
1

Whenever you have a series of items with a single key referencing multiple items, you can use a Lookup object:

var lookup = list.ToLookup( item => item.Sequence, item => item.Terms);

This code tells c# to create a lookup, which is just like a dictionary where item.Sequence is the key and item.Terms is the value. The value itself is a list which can be enumerated:

foreach (var item in lookup)
{
    Console.WriteLine("Sequence {0} has these terms: {1}", item.Key, string.Join(",", item));
}

Output:

Sequence 1438690 has these terms: weather,the elements
Sequence 9672410 has these terms: dogs,cats

See my working example on DotNetFiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80