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

本文是小编为大家收集整理的关于LINQ最大日期与分组的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

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

(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)

但是,我一直无法成功添加日期排序.我试图将日期列作为聚合添加到 group by 表达式中,但这不起作用.

(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)

我明白为什么它不起作用,我只是想不出另一种方法来添加二级排序.任何想法表示赞赏!

推荐答案

这就是你要找的(我认为)

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)

本文地址:https://www.itbaoku.cn/post/1557063.html

问题描述

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)

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)