Linq Multi-level Dynamic where子句

时间:2012-06-07 16:08:06

标签: c# linq

首先让我说我已经搜索并阅读了很多关于动态where子句的内容,以及ScottGu的博客和来自Albahari的PredicateBuilder类,但我不确定我是如何正确应用任何这些方法对我的情况。不知何故,我无法绕过它。

我有以下代码,在“静态”完成时可以正常工作:

var persons = from father in fathers
              select new                                
              {
                 Count = father.Sons
                                    .Select(son => son)
                                    .Where(son => son.Skills.Any(skill => skill.SkillType == "Languages" && skill.Name == "French"))
                                    .Where(son => son.Skills.Any(skill => skill.SkillType == "Sport" && skill.Name == "Football"))
                                    .Count(),

                 Name = father.Name
               };

但是,我想在运行时生成where子句。父对象具有Son对象的集合,而Son对象又具有Skills对象的集合。如查询所示,我想知道每个父亲的姓名和他们拥有一定技能的儿子的数量。这些技能将在运行时被选中,因此即使在示例中,我们只有两组技能(2 where子句),它可以是10或运行时的任意数量的子句。

我认为我最大的问题是我似乎无法根据我的情况调整StackOverflow上给出答案的例子,因为我需要从顶级(父亲)获取信息以及来自第3级的信息与二级(儿子)信息有关的等级(技能)。

如果需要,我会发布我明天已尝试过的示例代码。我现在不能这样做,因为我有点匆忙。任何帮助将非常感激。

修改

我需要的是一种在运行时连接where子句的方法,具体取决于用户选择了多少过滤条件。不同的过滤条件来自外部源并在运行时构建。例如:

在方案一中,可能有3个标准,例如用户选择的标准1,标准2和标准3。场景2可以有5个标准,比如标准1,标准2,...,标准5。第三种情况可能有10个标准,比如标准1,标准2,......,标准10。我需要的是能够为每个场景做以下事情,而不事先知道是否会有3,5,10或任何标准。

情景一:

var persons = from father in fathers
              select new                                
              {
                 Count = father.Sons
                                    .Select(son => son)
                                    .Where(criteria1)
                                    .Where(criteria2)
                                    .Where(criteria3)
                                    .Count(),

                 Name = father.Name
               };

情景2:

var persons = from father in fathers
              select new                                
              {
                 Count = father.Sons
                                    .Select(son => son)
                                    .Where(criteria1)
                                    .Where(criteria2)
                                    .Where(criteria3)
                                    .Where(criteria4)
                                    .Where(criteria5)
                                    .Count(),

                 Name = father.Name
               };

场景3:

var persons = from father in fathers
                  select new                                
                  {
                     Count = father.Sons
                                        .Select(son => son)
                                      .Where(criteria1)
                      .Where(criteria2)
                      .Where(criteria3)
                      .Where(criteria4)
                      .Where(criteria5)                   
                      .Where(criteria6)
                      .Where(criteria7)
                      .Where(criteria8)
                      .Where(criteria9)
                      .Where(criteria10)
                                  .Count(),
                     Name = father.Name
                   };

3 个答案:

答案 0 :(得分:2)

jonnyGold的答案很好,但它要求Son对象具有对父对象的引用。这是一个不需要的解决方案:

var query = from father in fathers
            from son in father.Sons
            select new {father, son};

foreach (Skill skillCriterion in CriterionSkills)
{
    var capturedSkillCriterion = skillCriterion;
    query = query.Where(fs => fs.son.Skills.Any(
        skill => skill.SkillType == capturedSkillCriterion.SkillType && 
                 skill.Name == capturedSkillCriterion.Name));         
}         

var persons = from fs in query
              group fs by fs.father into g 
              select new                                 
              { 
                 Count = g.Count(),
                 Name = g.Key.Name
              };

答案 1 :(得分:1)

var sons = fathers.SelectMany(f => f.Sons);

foreach(Skill skillCriterion in CriterionSkills)
{
    sons = sons.Where(son => son.Skills.Any(skill => skill.SkillType == skillCriterion.SkillType && skill.Name == skillCriterion.Name));
}

// we need to assume some sort of formal father-son relationship
var persons = from son in sons
              group son by new {son.Father.ID, son.Father.Name} into g
              select new
              {
                g.Key.Name,
                g.Count()
              };

答案 2 :(得分:0)

然后设计您的查询在哪里处理过滤器的动态性质。例如,我创造了父亲和儿子,儿子们可以在那里踢足球或排球。现在我的查询将采取只说足球的dyanmic请求...这是我如何做的:

void Main()
{
   bool findFootballers   = true;
   bool findVolleyBallers = false;

   var Fathers = new List<Father>()
   {
      new Father() { Name = "Frank SR", Sons = new List<Son>() { new Son() { Name = "Bob", PlaysFootball = true }, new Son() { Name = "Frank", PlaysVolleyBall = true } } },
      new Father() { Name = "Knute", Sons = new List<Son>() { new Son() { Name = "Mean Jo Green", PlaysFootball = true }, new Son() { Name = "McMann", PlaysFootball = true } } }
   };


   Fathers.Where (f => (findFootballers == false) ? true : f.Sons.Any (s => s.PlaysFootball == true))
          .Where (f => (findVolleyBallers == false) ? true : f.Sons.Any (s => s.PlaysVolleyBall == true))
          .Select( f => new
                       {
                       Name = f.Name,
                       TargetSportSons = string.Join(", ", f.Sons
                                                            .Where (s => (findFootballers == false) ? true : s.PlaysFootball)
                                                            .Where (s => (findVolleyBallers == false) ? true : s.PlaysVolleyBall)
                                                            .Select (s => s.Name))
                       }
                 )
            .ToList()
            .ForEach(fs => Console.WriteLine ("Father {0} has these sons {1} who play {2}", fs.Name, fs.TargetSportSons, (findFootballers ? "Football" : "VolleyBall ")));

// Output
// Father Frank SR has these sons Bob who play Football
// Father Knute has these sons Mean Jo Green, McMann who play Football

}

public class Son
{
   public string Name { get; set; }
   public bool PlaysFootball { get; set; }
   public bool PlaysVolleyBall { get; set;}
}


public class Father
{
   public string Name { get; set; }
   public List<Son> Sons = new List<Son>();

}

// Define other methods and classes here