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

4
  • 1
    Your question is not clear. Do you want <int, List<T>>? Commented Apr 15, 2019 at 3:59
  • I am not sure about the expected output. Commented Apr 15, 2019 at 4:06
  • .GroupBy(...) / group by ...? Commented Apr 15, 2019 at 4:07
  • can you share the input and expected output, you cant have a list that is composed of <int, string>, it's either <int> or <string> not both Commented Apr 15, 2019 at 4:09

3 Answers 3

3
var _result = termData.GroupBy(x => x.Sequence)
                .Select(x => new
                {
                    seq = x.Key,
                    term = x.Select(y => y.Term).ToList()
                });
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.