根据参数排除linq连接条件

Exclude linq join condition based on parameter

我希望能够根据布尔参数动态排除连接,请看下面的代码,如果 'includeJoin' 变量为假,我如何排除连接或者是否有其他动态添加连接的方法

 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() 来获取包含值的列表。