根据参数排除 linq 联接条件



我希望能够根据布尔参数动态排除连接,请查看下面的代码,如果"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; }
    }
}

我认为通过简单地构建两个不同的 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() 以获取包含值的列表。

最新更新