簡體   English   中英

動態Linq選擇復雜對象

[英]Dynamic Linq Select to a complex object

我有一個簡單的Linq查詢:

var retVal = readModel
    .GroupBy(x => x.Service)
    .Select(
        grp => new GroupView
        {
            GroupName = grp.Key,
            GroupItems = grp.Sum(k => k.NumberOfItems)
        }
    );

retVal是一個IQueryable<GroupView> 到目前為止,我正在嘗試做的是使這個查詢動態化,因此用戶可以使用自定義分組策略。

這是我的第一次嘗試:

var retVal = readModel
    .GroupBy("Service", "it")
    .Select("it.key");

這給了我一個包含組名的字符串數組。 這很好,但我想要實現的結果是相當遠的,因為我有兩個未提出的問題:

  • 如何將結果轉換為GroupView模型
  • 我該如何賺這筆錢?

事情是DynamicLinq不允許它簡單。

如果要擴展DynamicLinq庫以返回強類型結果,可以檢查此答案

但如果你不想要它,這是一個簡單的解決方案:

//select your grouped results
var retVal = readModel
        .GroupBy("Service", "it")
        .Select("new (it.key as GroupName, Sum(it.NumberOfItems) as GroupItems)");

//Map them
var res = ((IEnumerable<dynamic>)retVal)
          .Select(x => new GroupView 
                 { 
                    GroupName = x.GroupName, 
                    GroupItems = x.GroupItems 
                 });

暫無
暫無

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

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