小编ctk*_*ohn的帖子

LINQ - 编写扩展方法以获取每个组具有最大值的行

我的应用程序经常需要对表进行分组,然后返回该组的最大值.在LINQ中这很容易做到:

myTable.GroupBy(r => r.FieldToGroupBy)
.Select(r => r.Max(s => s.FieldToMaximize))
.Join(
    myTable,
    r => r,
    r => r.FieldToMaximize,
    (o, i) => i)
Run Code Online (Sandbox Code Playgroud)

现在假设我想将其抽象为自己的方法.我试着写这个:

public static IQueryable<TSource>
SelectMax<TSource, TGroupKey, TMaxKey>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, TGroupKey>> groupKeySelector,
    Expression<Func<TSource, TMaxKey>> maxKeySelector)
    where TMaxKey : IComparable
{
    return source
        .GroupBy(groupKeySelector)
        .Join(
            source,
            g => g.Max(maxKeySelector),
            r => maxKeySelector(r),
                (o, i) => i);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不能编译:maxKeySelector是一个表达式(所以你不能在r上调用它,你甚至无法将它传递给Max.所以我尝试重写,使maxKeySelector成为一个函数而不是一个表达式:

public static IQueryable<TSource>
SelectMax<TSource, TGroupKey, TMaxKey>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, TGroupKey>> groupKeySelector,
    Func<TSource, TMaxKey> maxKeySelector)
    where TMaxKey : IComparable
{
    return …
Run Code Online (Sandbox Code Playgroud)

c# linq linq-to-sql

5
推荐指数
1
解决办法
2122
查看次数

标签 统计

c# ×1

linq ×1

linq-to-sql ×1