Reputation: 24572
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
Upvotes: 0
Views: 557
Reputation: 52240
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
Upvotes: 1
Reputation: 43515
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
Upvotes: 2
Reputation: 139
var _result = termData.GroupBy(x => x.Sequence)
.Select(x => new
{
seq = x.Key,
term = x.Select(y => y.Term).ToList()
});
Upvotes: 3