LINQ对列表进行分组,并排除包含具有字段值的记录的组

xriantvc  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(113)

在设置我的lamda以排除具有带值字段的记录的组时遇到问题。我的数据示例:

CTY ProcId ProcTyp ProcDate
ZZZ 23-015 INIT    2023-01-26T20:04:30
ZZZ 23-015 UPDATE  2023-01-26T20:04:45
ZZZ 23-015 UPLOAD  2023-01-26T20:05:00
ZZZ 23-015 UPLOAD  2023-05-31T15:12:01
ZZZ 23-015 DELETE  2023-07-25T12:28:38

ZZZ 23-246 INIT    2023-11-07T23:31:09
ZZZ 23-246 DELETE  2023-11-08T16:49:55

ZZZ 23-248 INIT    2023-11-08T16:40:18
ZZZ 23-248 UPDATE  2023-11-08T16:43:14
ZZZ 23-248 UPLOAD  2023-11-08T16:43:35

字符串
我想做的是按CTY和ProcId对数据进行分组,然后获取MAX ProcDate。然而,必须从分组中忽略那些具有1个或多个ProcTyp = ''的组。我不只是想过滤掉这些记录,而是要过滤掉具有这些记录的GROUPS。在这种情况下,结果应该是一个列表:

CTY ProcId ProcTyp MaxProcDate 
ZZZ 23-248 UPLOAD  2023-11-08T16:43:35


我的C#代码:

var resListMax = resListAll
                .GroupBy(c => new { c.CTY, c.ProcId})
                .Select(g => new
                {
                    g.Key.CTY,
                    g.Key.ProcId,
                    MaxProcDate = g.Max(row => row.ProcDate),
                })
                .OrderBy(x => x.CTY).ThenBy(x => x.ProcId)
                .ToList();


我一直在看例子,但只是没有得到我应该把组过滤?我觉得这个post是我想要的,但不知道如何实现。任何帮助表示感谢。

rqqzpn5f

rqqzpn5f1#

您可以在.GroupBy()之后立即添加.Where()筛选器,以检查并排除包含 any“deleted”成员的组。

var resListMax = resListAll
                .GroupBy(c => new { c.CTY, c.ProcId})
                .Where(g => !g.Any(x => x.ProcTyp == "XWT.DELETE"))
                .Select(g => new
                {
                    g.Key.CTY,
                    g.Key.ProcId,
                    MaxProcDate = g.Max(row => row.ProcDate),
                })
                .OrderBy(x => x.CTY).ThenBy(x => x.ProcId)
                .ToList();

字符串
逻辑实际上是“只包括那些没有任何删除成员的组”。

9gm1akwq

9gm1akwq2#

谢谢你的输入。我决定用这个版本,因为它对我来说更容易阅读和维护。

var resListMax = resListAll
                .GroupBy(c => new { c.CTY, c.ProcId})
                .Select(g => new
                {
                    g.Key.CTY,
                    g.Key.ProcId,
                    MaxProcDate = g.Max(row => row.ProcDate),      // get the max time stamp in the group
                    HasDeletes = g.Any(x => x.ProcTyp == "DELETE") // gets a flag for any deletes in the group
                })
                .Where(x => !x.HasDeletes) // only include those groups without any deletes
                .OrderBy(x => x.CTY).ThenBy(x => x.ProcId)
                .ToList();

字符串

相关问题