在Linq中通过查询创建动态组

时间:2018-12-23 08:15:01

标签: c# linq

我有一个带有4个复选框的表格用于分组,当我想在where子句中创建LINQ动态查询时,使用这样的东西非常容易:

  query = query.where(x=>x.blah == blahblah).asQueryable();

但是我不能为Group by子句模拟这种类型的编码。我需要这样的东西:

if(blah1==true)
    query = query.GroupBy(x=>x.Blah1).select(smthing);
if(blah2==true)
    query = query.GroupBy(x=>x.Blah2).select(smthing);
if(blah3==true)
    query = query.GroupBy(x=>x.Blah3).select(smthing);
 ....

如何进行此类查询? stackoverflow中的某些帖子显示了令人误解的代码,例如Expression>。请向me显示一种简单且适用的方法。

1 个答案:

答案 0 :(得分:1)

这可能不是正确的做事方法,但是使用反射可以做事。因此,您所需要做的就是确定属性名称并将其传递给GroupBy

class Person
{
    public string Name { get; set; }
    public int Wage { get; set; }
    public int Age { get; set; }
    public override string ToString() =>
        $"Name: {Name}, Wage: {Wage}, Age: {Age}";
}

var list = new List<Person>
{
    new Person { Name = "Name1", Wage = 1, Age = 1},
    new Person { Name = "Name1", Wage = 2, Age = 2},
    new Person { Name = "Name2", Wage = 2, Age = 2},
    new Person { Name = "Name3", Wage = 2, Age = 2},
    new Person { Name = "Name3", Wage = 2, Age = 2},
    new Person { Name = "Name4", Wage = 2, Age = 2},
    new Person { Name = "Name4", Wage = 2, Age = 2}
};

var x = list.GroupBy(p => p.GetType().GetProperty("Name").GetValue(p));

foreach(var z in x)
{
    WriteLine(z.Key);
    foreach(var p in z)
    {
        WriteLine("\t" + p);
    }
}

/*
    Output:

Name1
      Name: Name1, Wage: 1, Age: 1
      Name: Name1, Wage: 2, Age: 2
Name2
      Name: Name2, Wage: 2, Age: 2
Name3
      Name: Name3, Wage: 2, Age: 2
      Name: Name3, Wage: 2, Age: 2
Name4
      Name: Name4, Wage: 2, Age: 2
      Name: Name4, Wage: 2, Age: 2
*/