C#linq group by字段和结果字符串?

时间:2015-05-09 14:16:06

标签: c# linq dynamic expression

如何使用selectfieldString和resultFieldString编写动态groupby? 样品:

       public class Customer
    {
        public int Id;
        public string Name;
        public string LastName;
        public decimal Amount;
    }
var lst = new List<Customer>();
        lst.Add(new Customer { Id = 1, Name = "vahid", LastName = "Aghilpour", Amount = 15 });
        lst.Add(new Customer { Id = 1, Name = "hamid", LastName = "rezaei", Amount = 35 });
        lst.Add(new Customer { Id = 1, Name = "vahid", LastName = "Aghilpour", Amount = 15 });


        string[] field = { "Name", "LastName" };
        string aggrigatefield = "Sum(Amount)";

        lst.GroupBy(field).Select(aggrigatefield);---??????????

1 个答案:

答案 0 :(得分:1)

使用dynamic linq你应该可以做到。

// Remember: using System.Linq.Dynamic;
// The format for the key of the GroupBy is "new(field1,field2)"
// "it" as elementSelector means "the full object"
string field = string.Format("new({0})", string.Join(",", fields));
decimal[] res = lst.GroupBy(field, "it")
                   .Select(aggrigatefield)
                   .Cast<decimal>()
                   .ToArray();

请注意,如果Select完全是动态的(因此它可能会返回Sum()string字段,decimal字段,或复杂对象或a ???),然后你不能真正做Cast<decimal>(),因为你“静态地”不知道返回对象的类型。你必须这样做

object[] res = lst.GroupBy(field, "it")
                  .Select(aggrigatefield)
                  .Cast<object>()
                  .ToArray();

dynamic[] res = lst.GroupBy(field, "it")
                  .Select(aggrigatefield)
                  .Cast<dynamic>()
                  .ToArray();