2015-12-15 67 views
0

我有基於某些ID或字符串值,我想如何使用lambda表達式改變計算類型?

var result = from r in mlist 
      group r by new 
        { 
         r.ParameterId, 
         r.WId, 

        } into g 
      select new 
        { 
         g.Key.ParameterId, 
         g.Key.WId, 
         Value = g.Sum(x => x.Value) 
        }; 

在組改變計算類型列表,我想用一個自定義的方法,該方法將返回基礎計算的結果來替換這個LINQ總和像一些平均計算類型,總結等

可能是這樣的:

var result = from r in mlist 
      group r by new 
        { 
         r.ParameterId, 
         r.WId, 
        } into g 
      select new 
        { 
         g.Key.ParameterId, 
         g.Key.WId, 
         Value = g.CustomMethod(x => x.Value, x.calctype) 
        }; 
+0

難道這會打的數據庫?或者在記憶中?無論如何,就像在自定義方法中寫入'if' /'switch'語句一樣簡單。 – Rob

+0

第二個'x'來自'g.CustomMethod(x => x.Value,x.calctype)''?也許可以用'calctype'作爲關鍵字在字典中添加所有可能的函數。在這種情況下,你可以稱它爲'dict [g,x => x.Value]'。使用它你不能稱之爲擴展方法。 –

+0

您是否需要將x.value和x.calctype專門傳遞給CustomMethod?如果您有權訪問CustomMethod中的完整r對象,它不會起作用嗎? – sachin

回答

3

可以擴展集,您可以通過阿迪使用LINQ查詢方法將擴展方法擴展到IEnumerable接口。例如,除了標準的平均值或最大值操作之外,您還可以創建一個自定義聚合方法來根據一系列值計算單個值。您還可以創建一個方法,用作一系列值的自定義過濾器或特定數據轉換,並返回一個新序列。

public static class LINQExtension 
{ 
    public static double Median(this IEnumerable<double> source) 
    { 
     if (source.Count() == 0) 
     { 
      throw new InvalidOperationException("Cannot compute median for an empty set."); 
     } 

     var sortedList = from number in source 
         orderby number 
         select number; 

     int itemIndex = (int)sortedList.Count()/2; 

     if (sortedList.Count() % 2 == 0) 
     { 
      // Even number of items. 
      return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1))/2; 
     } 
     else 
     { 
      // Odd number of items. 
      return sortedList.ElementAt(itemIndex); 
     } 
    } 
} 

Source: Add Custom Methods for LINQ Queries

您還想查看Create the function using Expression linq

0

我想你應該寫自己的extention方法,somethig這樣的:

public static class MyEnumerable 
{ 
    public static int CustomMethod<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector, Func<TSource, int> type) 
    { 
     var sum = 0; 
     source.ToList().ForEach(x => sum += selector(x) * type(x)); 
     return sum; 
    } 
} 

你會執行它本方式,您的第二個代碼清單將不會被編譯:

Value = g.CustomMethod(x => x.Value, x => x.calctype) 

如果你想爲你可以這樣寫所有的項目之一calctype:

Value = g.CustomMethod(x => x.Value, x => 123);