簡體   English   中英

LINQ:方法&#39;GroupBy&#39;的重載沒有6個參數/ IGrouping <t,t> 不包含定義

[英]LINQ: No overload for method 'GroupBy' takes 6 arguments / IGrouping<t,t> does not contain a definition

問題:出現錯誤

“方法'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中使用

您需要創建一個匿名對象,其中包含要包含在group by中的所有字段的列表,然后使用分組列表的Key屬性訪問這些字段,如下所示-

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

因此, GroupBy的輸入是一系列Views 每個View至少都有一個StartDateSomeId

您的GroupBy將所有輸入的Views分組為從具有相同StartDateViews提取的項目組。 每個組都有一個包含此公共StartDateKey ,該組中的元素是該組中ViewsSomeId

GroupBy的結果已經是IQueryable<...> 因此, AsQueryable是不必要的,只會減慢您的處理速度。

您的Orderby的輸入是一組序列。 groups,群組沒有StartDate 幸運的是,組具有包含您要作為排序依據的StartDateKey

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

順便說一句,如果您不想要Key ,而是堅持擁有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

更新:

您的代碼中有簡單的問題,請將代碼更改為此:

var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
                   .Select(g => new
                       {
                           Id = g.Key.Id,
                           Name = g.Key.Name,
                           Count = g.Count()
                       });

grouping完成后,您必須像我的樣本一樣新建並設置數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM