user1662812
user1662812

Reputation: 2601

Group By List with Lambda

I have a simple object:

public class obj
    {
        public Int32 id { get; set; }

        public Int32 source { get; set; }
}

Now I have a list: List<obj> of 10 objects, 5 of them have source set to 100, 3 have source set to 200 and 2 have source set to 2500

I need to group by the source which will result in three items 100, 200 and 2500. Also I need to order by count, like this:

5 100
3 200 
2 2500

The end result is that I want to get the source with the top count, which in this case will be 100

Upvotes: 0

Views: 6854

Answers (2)

Tormod
Tormod

Reputation: 4573

var res = lst.GroupBy(o=>o.source)
             .Select(grp=>new {Count=grp.Count(),Source=grp.Key});

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

This will give you source with top count:

int topSource = list.GroupBy(o => o.source)
                    .OrderByDescending(g => g.Count())
                    .First()
                    .Key;

Explanation

  • Group items by source value (it will create three groups)
  • Order groups by items count in each group
  • Select first group (it will have max items count)
  • Get grouping key (which is source value)

Upvotes: 3

Related Questions