开发者

How can I get a distinct count of a field using linq?

What I am trying to do is figure out a vote result with linq. Every user has a beerID that is the beer they 开发者_如何学编程voted for or null if they didn't vote. I feel like this should be simple but for the life of me I can;t figure it out right now. Is there a quick way using linq that I can get the count of each unique beerID and then get the one with the most votes?


Users
    .GroupBy(u => u.beerID)
    .Select(g => new {beerId = g.Key, count = g.Count()})
    .OrderByDescending(x => x.count)
    //.FirstOrDefault()


Grouping is probably your best bet - group the votes by beer ID, and then count the items in each group. Something like this, for example:

var beerCounts = from vote in votes
                 where vote.BeerID != null
                 group vote by vote.BeerID into beerVoteGroups
                 select new
                 {
                     Count = beerVoteGroups.Count(),
                     BeerID = beerVoteGroups.Key
                 };

foreach (var group in beerCounts)
{
    Console.WriteLine("Beer {0} got {1} votes", group.BeerID, group.Count);
}

Getting the most votes can be done by ordering the results. Here's a modified query that sorts the beers by how many votes the got, starting with the winner.

var beerCounts = from vote in votes
                 where vote.BeerID != null
                 group vote by vote.BeerID into beerVoteGroups
                 let voteCount = beerVoteGroups.Count()
                 orderby voteCount descending 
                 select new
                 {
                     Count = voteCount,
                     BeerID = beerVoteGroups.Key
                 };

You could then pick the winner by using the LINQ First operator, e.g.:

var winner = beerCounts.First();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜