Dynamic Linq任何语法

时间:2014-01-28 10:50:22

标签: linq dynamic-linq

我想弄清楚如何在Linq.Dynamic中使用Any运算符,这是我的测试代码:

var bar = new[] {
    new {Bar = "A", Id = 1},
    new {Bar = "B", Id = 1},
    new {Bar = "C", Id = 2},
    new {Bar = "A", Id = 2},
    new {Bar = "B", Id = 3},
    new {Bar = "C", Id = 3}
}; 
var foo = new[] {
    new {Foo = 1, Id = 1},
    new {Foo = 1, Id = 1},
    new {Foo = 2, Id = 2},
    new {Foo = 2, Id = 2},
    new {Foo = 2, Id = 3},
    new {Foo = 3, Id = 3}
}; 
var res = foo.GroupJoin(bar, x => x.Id, y => y.Id, (x, l) => new { F = x.Foo, Bs = l.Select(b => b.Bar).ToArray() }).ToArray();
var normalLinq = res.Where(x => x.Bs.Any(y => y == "A")).ToArray();
var dynamicLinq = res.AsQueryable().Where("Bs.Any(x => x==\"A\")").ToArray(); //won't work

语法"Bs.Any(x => x==\"A\")"是错误的,因为动态linq似乎不知道我放入的lambda表达式,并抛出异常。我如何使它工作?

我的目标是使用此代码解析动态搜索输入。如果Linq专家有其他更好的方法进行动态搜索,请建议吗?

1 个答案:

答案 0 :(得分:2)

如果您正在使用此库:http://www.nuget.org/packages/System.Linq.Dynamic/据我所知它不允许使用lambda表达式。但是,有人扩展了这个库。我从来没有尝试过,但看起来很有希望。 http://dynamiclinq.codeplex.com/祝你好运:)