EF十大最受欢迎地点c#

时间:2019-04-05 09:46:28

标签: c# linq tsql

我有一个表tbLocations,其中包含以下列:

int           id      {PRIMARY_KEY, AUTO_INCREMENT}
int           userid  {Foreign key with table_users}
varchar(200)  location

在此表中,我有以下几行:

1, 1, New York
2, 1, California
3, 1, Seattle
4, 1, New York
5, 2, Seattle
6, 2, Ontario
7, 3, Chicago
8, 4, Las Vegas
9, 5, New York

我想创建一个C#linq查询,该查询可以让我获得前10个位置,对于我而言,我应该得到

New York  2
Seattle   2

这里的问题是用户i.e. New York is duplicate for userid 1的位置可以重复,所以我不希望这样的重复影响最终报告。

就像在最终报告中一样,我的纽约= 2,而不是= 3

如何在LINQ中做到这一点?

我真的不知道从哪里开始,我通过分组进行了尝试,但是没有用

2 个答案:

答案 0 :(得分:2)

从此查询开始:

select top 10 count(*) cnt, [location] from 
     (
     select count(*) as dupl, userid, [location]
     from tbLocations
     group by userid,  [location]
     ) as test
 group by [location]
 order by cnt desc

这给出了以下结果:

cnt location
2   New York
2   Seattle
1   Ontario
1   California
1   Chicago
1   Las Vegas

答案 1 :(得分:1)

这里是my solution

var locations = new List<Location>
{
    new Location{ Id = 1, UserId = 1, Name = "New York" },
    new Location{ Id = 2, UserId = 1, Name = "California" },
    new Location{ Id = 3, UserId = 1, Name = "Seattle" },
    new Location{ Id = 4, UserId = 1, Name = "New York" },
    new Location{ Id = 5, UserId = 2, Name = "Seattle" },
    new Location{ Id = 6, UserId = 2, Name = "Ontario" },
    new Location{ Id = 7, UserId = 3, Name = "Chicago" },
    new Location{ Id = 8, UserId = 4, Name = "Las Vegas" },
    new Location{ Id = 9, UserId = 5, Name = "New York" },
};

var topLocations = locations
    .GroupBy(location => new { location.UserId, location.Name })
    .Select(group => group.First())
    .GroupBy(location => location.Name)
    .Select(group => new { group.Key, Count = group.Count() })
    .OrderByDescending(location => location.Count)
    .Take(2);

foreach (var item in topLocations)
{
    Console.WriteLine($"{item.Key} {item.Count}");
}