LINQ最大日期与分组依据 [英] LINQ Max Date with group by

查看:57
本文介绍了LINQ最大日期与分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求对列表进行以下排序:1)出现不同项目的次数,然后2)如果两个不同行的计数相同(该组的最近使用日期).

I have a requirement to sort a list by 1) the number of times a distinct item appears and then 2) if the count of two distinct rows is the same, the most recently used date of that group.

我的按功能分组和按计数排序的工作没有日期:

My group by function and sorting by count is working without the date:

(from x in data
group x by new { x.Col1, x.Col2, x.Col3} 
into g
let count = g.Count()
select new
{
    g.Key.Col1,
    g.Key.Col2,
    g.Key.Col3,
    count
}).OrderByDescending(x => x.count)

但是,我无法成功添加日期排序.我试图将date列添加为按表达式分组的汇总,但这是行不通的.

However, I have been unable to successfully add the date sort. I was trying to add the date column as an aggregate in the group by expression, but that doesn't work.

(from x in data
group x by new { x.Col1, x.Col2, x.Col3, MaxDate = x.CreatedDateTime.Max()}
into g
let count = g.Count()
select new
{
    g.Key.Col1,
    g.Key.Col2,
    g.Key.Col3,
    count,
    g.Key.MaxDate
}).OrderByDescending(x => x.count).ThenByDescending(x => x.MaxDate)

我知道为什么它不起作用,我只是想不出另一条添加第二种排序的途径.任何想法表示赞赏!

I get why it doesn't work, I just can't think of another route to add the secondary sort. Any ideas are appreciated!

推荐答案

这是您正在寻找的(我认为)

This is what you're looking for (I think)

from x in data
group x by new { x.Col1, x.Col2, x.Col3} 
into g
let count = g.Count()
select new
{
    g.Key.Col1,
    g.Key.Col2,
    g.Key.Col3,
    MaxDate = g.Select(x => x.CreatedDateTime)
               .OrderByDescending(d => d).FirstOrDefault(),
    count
}).OrderByDescending(x => x.count).ThenByDescending(x => x.MaxDate)

这篇关于LINQ最大日期与分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆