1

I have got a list which looks like this for example:

Id = 1, Name = Microsoft, Country = USA, Match = null
Id = 2, Name = Google,    Country = USA, Match = null
Id = 1, Name = Microsoft, Country = USA, Match = null

Now I would like to group the list by name which I did like this:

var List = result.GroupBy(x => x.Name).ToList();

My goal is to safe the number of duplicates into Match. So that the list looks like this:

Id = 1, Name = Microsoft, Country = USA, Match = 2
Id = 2, Name = Google,    Country = USA, Match = 1

Thanks in advance!

1 Answer 1

7

I would group by all three properties thus they will have same values for all item in the group. That will simplify building aggregated entity:

var List = result.GroupBy(x => new { x.Name, x.Id, x.Country })
             .Select(g => new YourType { 
                 Id = g.Key.Id,
                 Name = g.Key.Name,
                 Country = g.Key.Country,
                 Match = g.Count()
             })
             .ToList();

If you have Microsoft in other countries (not only USA) and you want to get the number of duplicates for company Name only (whether it is located in USA or not), then you should remove Country both from key and from aggregated entity.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that did it!
If I only want to group by Name and not by Country but still want to include the country in the list how would I do that?
@Anokrize then you should define which Country you want to include. Because there will be several entities with same name, but different countries

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.