2012-09-12 39 views
4

我正在使用Dynamic Linq助手来分组数据。我的代码如下:动态Linq Groupby SELECT键,列表<T>

Employee[] empList = new Employee[6]; 
empList[0] = new Employee() { Name = "CA", State = "A", Department = "xyz" }; 
empList[1] = new Employee() { Name = "ZP", State = "B", Department = "xyz" }; 
empList[2] = new Employee() { Name = "AC", State = "B", Department = "xyz" }; 
empList[3] = new Employee() { Name = "AA", State = "A", Department = "xyz" }; 
empList[4] = new Employee() { Name = "A2", State = "A", Department = "pqr" }; 
empList[5] = new Employee() { Name = "BA", State = "B", Department = "pqr" }; 

var empqueryable = empList.AsQueryable(); 
var dynamiclinqquery = DynamicQueryable.GroupBy(empqueryable, "new (State, Department)", "it"); 

我怎样才能找回分组的项目中的重点和相应的清单即{重点,列出}的IEnumerable的从dynamiclinqquery?

+0

By DynamicQueryable你指的是这个类吗? http://code.google.com/p/codesmith/source/browse/branches/DbContext-Test/Source/EntityFramework.Extended/Dynamic/DynamicQueryable.cs?r=2377&spec=svn2377 – Rockstart

回答

8

我定义的问题解决了一个选择器,用于投影Key以及Employees List。

 var eq = empqueryable.GroupBy("new (State, Department)", "it").Select("new(it.Key as Key, it as Employees)"); 
     var keyEmplist = (from dynamic dat in eq select dat).ToList(); 

     foreach (var group in keyEmplist) 
     { 
      var key = group.Key; 
      var elist = group.Employees; 

      foreach (var emp in elist) 
      { 

      }           
     } 
0

GroupBy方法仍应返回实现IEnumerable<IGrouping<TKey, TElement>>的东西。

虽然你可能无法真正它(我假设它是dynamic),你当然可以仍就调用它,就像这样:

foreach (var group in dynamiclinqquery) 
{ 
    // Print out the key. 
    Console.WriteLine("Key: {0}", group.Key); 

    // Write the items. 
    foreach (var item in group) 
    { 
     Console.WriteLine("Item: {0}", item); 
    } 
} 
+1

谢谢卡斯帕尔。 DynamicQueryable抛出System.Linq.Lookup .Grouping。 – ideafountain

+0

@idea除此之外,你还在寻找什么? – casperOne

+1

由于DynamicQueryable创建的运行时类型,我无法使用由DynamicClass表示的Key。可能有一种方法来处理它,但我发现的工作是与Employee列表一起显式地在动态选择器中投影Key。感谢您投入。 – ideafountain