Alan2
Alan2

Reputation: 24572

How can I combine data from rows in a list using LINQ?

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

Upvotes: 0

Views: 557

Answers (3)

John Wu
John Wu

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

Theodor Zoulias
Theodor Zoulias

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

Makarov2015
Makarov2015

Reputation: 139

var _result = termData.GroupBy(x => x.Sequence)
                .Select(x => new
                {
                    seq = x.Key,
                    term = x.Select(y => y.Term).ToList()
                });

Upvotes: 3

Related Questions