首页 > 解决方案 > LINQ:方法“GroupBy”没有重载需要 6 个参数/IGrouping不包含定义

问题描述

问题:出现错误

“方法 'GroupBy' 没有重载需要 6 个参数”

很多 SO 文章都是针对特定用户创建的方法。GroupBy 是库的一部分。

我试过改变参数的数量。如果我将其更改为 2 个参数,则错误指向它具有 OrderByDescending 的下一个区域并给出错误:

“IGrouping 不包含‘Start_Date’的定义,并且找不到接受‘IGrouping’类型的第一个参数的扩展方法‘Start_Date’。”

给出此错误的代码是:

var someVariable = DbContextObject.View.Where(
                        m =>
                            m.Some_ID == CurrentlyEditingSomeID
                        ).GroupBy(d=> d.Start_Date,f=>f.Some_ID).AsQueryable().OrderByDescending(m => m.Start_Date);

在 ListView 中使用

标签: c#asp.netlinqiqueryableigrouping

解决方案


所以你的输入GroupBy是一个序列Views。每个View至少有一个StartDateSomeId

您的GroupBy组都输入到从相同Views的 中提取的项目组中。每个 Group 都有一个包含这个 common的,组中的元素是组中的。ViewsStartDateKeyStartDateSomeIdViews

的结果GroupBy已经是IQueryable<...>。所以AsQueryable是不必要的,它只会减慢你的进程。

您的输入Orderby是一组组。唉,团体没有StartDate. 幸运的是,组有一个Key包含StartDate您想要订购的。

var result = DbContextObject.Views
    // I onlly want the views with a certain SomeId:
    .Where(view => view.SomeID == CurrentlyEditingSomeID)

    // group the views into groups with same StartDate
    // the elements in the group are the SomeId
    .GroupBy(view => view.StartDate, view=>view.SomeID)
    // result: a sequence of Groups with a Key and a sequence of SomeId objects

    // order the Groups by StartDate, This StartDate is in the Key
    .OrderBy(group => group.Key);

顺便说一句,如果您不想要 aKey并坚持拥有 a StartDate,则GroupBy 的重载则鲜为人知。一个版本,您可以在其中选择您想要的输出。

.GroupBy(view = view.StartDate,         // make groups with same StartDate
    view => view.SomeId,                // select SomeId as elements in the group
    (commonStartDate, someIds) => new   // from every commonStartDate and the someIds
    {                                   // in this group make a new object
        StartDate = commonstartDate,    // containing this common StartDate
        SomeIds = someIds,              // and the SomeId objects in the group
    })
    .OrderBy(group => group.StartDate); // now you can order by StartDate instead of Key

推荐阅读