2013-07-04 248 views
0

我想通過linq查詢在數據表中按多列進行分組。group by linq查詢

我試過這樣的,

var _result = from row in tbl.AsEnumerable() 

group row by new 
{ 
    id=row.Field<object>(_strMapColumn), 
    value=row.Field<object>(_strValueColumn), 
} into g 
select new 
{ 
    _strMapColumn = g.Key.id, 
    ToolTip = g.Sum(r => grp.Sum(r => r.Field<Double>(__strToolTip[1]))), 
}; 

其工作正常。我的問題是我有一個strToolTip數組中的10個列名我想訪問10個列名稱動態像循環是可能的嗎?

我想這樣

select new 
{_strMapColumn = g.Key.id, 

    for(int index = 1; index <= 10; index++) 
    {  
     ToolTip+index = g.Sum(r => getDoubleValue(r.Field<Double>(__strToolTip[1]))) 
    } 
}; 

,也想添加一個數據類型動態請您提供答案爲解決這個問題。 linq查詢對我來說是新的。

回答

0

你可以通過字典組,並通過自定義比較:

public class MyComparer : IEqualityComparer<Dictionary<string, object>> { 
    public bool Equals(Dictionary<string, object> a, Dictionary<string, object> b) { 
     if (a == b) { return true; } 
     if (a == null || b == null || a.Count != b.Count) { return false; } 
     return !a.Except(b).Any(); 
    } 
} 

IEnumerable<string> columnsToGroupBy = ... 
var rows = tbl.AsEnumerable(); 
var grouped = rows.GroupBy(r => columnsToGroupBy.ToDictionary(c => c, c => r[c]), new MyComparer()); 
var result = grouped.Select(g => { 
    // whatever logic you want with each grouping 
    var id = g.Key["id"]; 
    var sum = g.Sum(r => r.Field<int>("someCol")); 
}); 
0

感謝ChaseMedallion,我得到了動態分組工作。 等於方法是不夠的,我不得不增加GetHashCodeMyComparer以及:

public int GetHashCode(Dictionary<string, object> a) 
{ 
    return a.ToString().ToLower().GetHashCode(); 
}