根据参数排除linq连接条件

时间:2015-06-19 04:43:54

标签: c# .net linq linq-to-sql

我希望能够根据布尔参数动态排除连接,查看下面的代码,如果' includeJoin'变量是false或是否有另一种动态添加连接的方法

 class Program
{
    static void Main(string[] args)
    {
        List<Foo> fooList = new List<Foo>();
        fooList.Add(new Foo{Foo_Id = 1});
        fooList.Add(new Foo{Foo_Id = 2});

        List<Bar> barList = new List<Bar>();
        barList.Add(new Bar{Foo_Id = 1});
        barList.Add(new Bar{Foo_Id = 1});

        IQueryable<Foo> fooQuery = fooList.AsQueryable();
        IQueryable<Bar> barQuery = barList.AsQueryable();

        bool includeJoin = false;

        var foos = from f in fooList

                   //Exclude this join if includeJoin vairable is false!!
                   join b in barList on f.Foo_Id equals b.Foo_Id into g
                   from result in g.DefaultIfEmpty()


                   select new Foo { Foo_Id = f.Foo_Id };

        var results = foos.ToList();
    }

    public class Foo
    {
        public int Foo_Id { get; set; }
    }

    public class Bar
    {
        public int Foo_Id { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为只需构建两个不同的LINQ查询即可实现所需:

bool includeJoin = false;

IEnumerable<Foo> foos;

if (includeJoin)
{
    foos = from f in fooList

                //Exclude this join if includeJoin vairable is false!!
                join b in barList on f.Foo_Id equals b.Foo_Id into g
                from result in g.DefaultIfEmpty()


                select new Foo { Foo_Id = f.Foo_Id };
}
else
{
    foos = from f in fooList select new Foo { Foo_Id = f.Foo_Id };
}

var results = foos.ToList();

使用此解决方案,您可以简单地构建两个独立的LINQ查询,这将以任一方式产生IEnumerable。由于它们都导致相同的类型(IEnumerable),因此您可以在末尾使用foos.ToList()来获取带有值的列表。