LINQ表达式将匹配多个批量输入

时间:2016-09-03 11:34:11

标签: c# entity-framework linq

如何编写一个匹配多个批量输入的LINQ表达式?

这是我的数据库表

Members
Division, Department
1           3
4           9       *
5           1
6           3       *
9           2

我想选择标有*

的成员

以下是我的输入

int[] divisions = new int[2] {4, 6};
int[] department = new int[2] {9, 3};

这是我试过的查询

var selectedMembers = members.Where(member => divisions.Contains(member.Division) && department.Contains(member.Department)).ToArray();

这在EF中表现不正常。单个输入但不是两个输入时都可以工作(分部和部门) 它应返回输入中匹配的对 例如:

Member[] selectedMembers = new Member[2] { new Member{Division=4,Department=9}, new Member{Division=6,Department=3}};

3 个答案:

答案 0 :(得分:2)

尝试

var member = members.Where(member => divisons.Contains(member.Division) && department.Contains(member.Department)).ToList();

您使用了Select条款,我已经修改过Where

答案 1 :(得分:1)

EF不直接支持此类过滤。

一种可能的解决方案是动态构建这样的谓词:

member => (member.Division == divisions[0] && member.Department == departments[0])
       || (member.Division == divisions[1] && member.Department == departments[1])
       ...
       || (member.Division == divisions[N-1] && member.Department == departments[N-1]);

以下是如何做到这一点:

var parameter = Expression.Parameter(typeof(Member), "member");
var predicate = Expression.Lambda<Func<Member, bool>>(
    Enumerable.Range(0, divisions.Length)
    .Select(i => new Expression[]
    {
        Expression.Equal(Expression.Property(parameter, "Division"), Expression.Constant(divisions[i])),
        Expression.Equal(Expression.Property(parameter, "Department"), Expression.Constant(departments[i])),
    }
    .Aggregate(Expression.AndAlso))
    .Aggregate(Expression.OrElse),
    parameter);
var query = members.Where(predicate);

答案 2 :(得分:0)

这与@Robert的答案类似,但会过滤结果以确保分部和部门相同&#34;配对&#34;:

int[] divisons = { 4, 6 }, departments = { 9, 3 };
var members = new[] { new { Division = 1, Department = 2 } }; // just for testing

var query = members.Where(m => divisons.Contains(m.Division) 
                         && departments.Contains(m.Department));

var member = query.AsEnumerable().Where(m => Array.IndexOf(divisons, m.Division) 
                        == Array.IndexOf(departments, m.Department));