4

我正在使用动态 Linq 助手对数据进行分组。我的代码如下:

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

如何从 dynamiclinqquery 取回分组项目的密钥和相应列表,即 {Key, List} 的 IEnumerable ?

4

2 回答 2

8

我通过定义一个投影键和员工列表的选择器解决了这个问题。

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

           }                                          
       }
于 2012-09-19T15:45:15.810 回答
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);
    }
}
于 2012-09-14T19:23:57.297 回答