c# - GroupBy 复杂查询

标签 c# asp.net-mvc linq

我已经为统计页面创建了一个 View 模型,如下所示:

public class StatsSeasonViewModel
{
    public int player_id { get; set; }
    public string player_name { get; set; }
    public int games_played { get; set; }
    public int total_first { get; set; }
    public int total_second { get; set; }
    public int total_third { get; set; }
    public int total_wickets { get; set; }
    public double avg_wickets { get; set; }
    public int total_points { get; set; }
    public double avg_points { get; set; }
}

我有一个复杂的 LINQ 语句来填充模型。我觉得这可能更简单,但我不知道该怎么做:

const int first_place = 5;
const int second_place = 3;
const int third_place = 1;

var model =
from s in _db.Stats
join p in _db.Players
on s.player_id equals p.player_id
where s.season_id == current_season
select new StatsSeasonViewModel
{
    player_id = p.player_id,
    player_name = p.name,
    games_played = (from st1 in _db.Stats
                    where st1.player_id == s.player_id
                    select st1).Count(),
    total_first = (from st2 in _db.Stats
                    where st2.player_id == s.player_id && st2.place == 1
                    select st2).Count(),
    total_second = (from st3 in _db.Stats
                    where st3.player_id == s.player_id && st3.place == 2
                    select st3).Count(),
    total_third = (from st4 in _db.Stats
                    where st4.player_id == s.player_id && st4.place == 3
                    select st4).Count(),
    total_wickets = (from st5 in _db.Stats
                        where st5.player_id == s.player_id
                        select st5.wickets).Sum(),
    avg_wickets = (from st5 in _db.Stats
                    where st5.player_id == s.player_id
                    select st5.wickets).Sum() /
                    (from st1 in _db.Stats
                    where st1.player_id == s.player_id
                    select st1).Count(),
    total_points = (from st5 in _db.Stats
                    where st5.player_id == s.player_id
                    select st5.wickets).Sum() +
                    (
                        (from st2 in _db.Stats
                            where st2.player_id == s.player_id && st2.place == 1
                            select st2).Count()
                    ) * first_place +
                    (
                        (from st3 in _db.Stats
                            where st3.player_id == s.player_id && st3.place == 2
                            select st3).Count()
                    ) * second_place +
                    (
                        (from st4 in _db.Stats
                            where st4.player_id == s.player_id && st4.place == 3
                            select st4).Count()
                    ) * third_place,
    avg_points = (
                    (from st5 in _db.Stats
                        where st5.player_id == s.player_id
                        select st5.wickets).Sum() +
                    (
                        (from st2 in _db.Stats
                            where st2.player_id == s.player_id && st2.place == 1
                            select st2).Count()
                    ) * first_place +
                    (
                        (from st3 in _db.Stats
                            where st3.player_id == s.player_id && st3.place == 2
                            select st3).Count()
                    ) * second_place +
                    (
                        (from st4 in _db.Stats
                            where st4.player_id == s.player_id && st4.place == 3
                            select st4).Count()
                    ) * third_place
                ) /
                (from st1 in _db.Stats
                    where st1.player_id == s.player_id
                    select st1).Count()
};

所以我现在遇到的最大问题是我需要对这个查询进行分组,这样它就不会显示重复项。但是当我尝试添加组依据时,我不知道如何在 SELECT 之后执行其余查询。如何对上述查询进行分组并获得我需要的结果?

编辑:FWIW 这是我得到的结果:http://ecl.moyl.com/Home/Stats

第二个问题当然是查询本身的复杂性。有更简单的方法吗?

最佳答案

有几种方法可以简化事情,但要回答您的主要问题:

var search = from st2 in _db.Stats
    where st2.player_id = s.player_id
    group st2 by st2.player_id

您将遍历每个组以获得 IGrouping<TKey, TElement>获取个人计数 ( ref )。

for (var playerGroup in search)
{
     Console.WriteFormat("{0}: {1}\n", playerGroup.Key, playerGroup.Count());
}

如果您使用稍微不同的方式来编写您的计数/总和,您的代码可能会更具可读性。

例如,这个:

games_played = (from st1 in _db.Stats
                where st1.player_id == s.player_id
                select st1).Count(),
total_wickets = (from st5 in _db.Stats
                    where st5.player_id == s.player_id
                    select st5.wickets).Sum()

可以变成这样:

var filter = st => st.player_id == s.player_id; // reuse this over and over

games_played = _db.Stats.Where(filter).Count(),
total_wickets = _db.Stats.Where(filter).Sum(st5 => st5.wickets)

事实上,为了“吃蛋糕也吃蛋糕”,当您使用 group by 语句时,整个过滤器就变得不必要了。您必须更改创建模型的方式,以便可以传入 IGrouping<int,Stat> (假设这就是类型)到构造函数。在这种方法中,您的整体查询如下所示:

const int first_place = 5;
const int second_place = 3;
const int third_place = 1;

var model =
    from s in _db.Stats
    join p in _db.Players
    on s.player_id equals p.player_id
    where s.season_id == current_season
    group st by st.player_id into group
    select new StatsSeasonViewModel(group)

现在您的 StatsSeasonViewModel负责根据组中的值填充其统计数据

 public StatsSeasonViewModel(IGrouping<int,Stat> playerStats)
 {
     player_id = playerStats.Key;
     games_played = playerStats.Count();
     total_wickets = playerStats.Sum(st=>st.wickets);
     // ....
 }

关于c# - GroupBy 复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125489/

相关文章:

c# - Windows 身份验证不断询问用户名密码,即使凭据正确

c# - Environment.UserName 为同一用户(大小写)提供不同的结果 : alternative/transformation?

c# - 如何为此单元测试实现模拟?

c# - 使用 TempData 从 MVC 操作向 ViewBag 添加字符串值时出现问题

c# - DbExpressionBinding 需要一个带有集合 ResultType 的输入表达式

c# - 创建不具有实体类型属性的动态 LINQ 语句

c# - 具有 WCF 的脚本组件 app.config 中的合约属性无效

javascript - tinymce 与 mvc 没有选择器名称称为tinymce-textarea?

asp.net-mvc - 使用 Asp.net Mvc 的缩略图

linq - 扩展基于 LINQ 的规范模式以实现包含