动态LINQ:将嵌套数据与父属性进行比较

时间:2015-01-01 08:40:47

标签: linq c#-4.0 lambda expression dynamic-linq

我有一个具有以下结构的课程:

 public class BestWayContext
{
    public Preference Preference { get; set; }
    public DateTime DueDate { get; set; }
    public List<ServiceRate> ServiceRate { get; set; }
}

public class ServiceRate
{
    public int Id { get; set; }
    public string Carrier { get; set; }
    public string Service { get; set; }
    public decimal Rate { get; set; }
    public DateTime DeliveryDate { get; set; }
}

我有动态linq表达式字符串

“偏好!= null&amp;&amp; ServiceRate.Any(Carrier == Preference.Carrier)”

我想在Dynamic LINQ中转换上面的字符串,如下所示:

  var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, null).Compile();

但它显示以下错误:

enter image description here

请纠正我,我做错了什么?

2 个答案:

答案 0 :(得分:0)

看起来你想做这样的事情:

var bwc = new BestWayContext
{
    Preference = new Preference { Carrier = "test" },
    DueDate = DateTime.Now,
    ServiceRate = new List<ServiceRate>
    {
        new ServiceRate
        {
            Carrier = "test",
            DeliveryDate = DateTime.Now,
            Id = 2,
            Rate = 100,
            Service = "testService"
        }
    }
};

string condition = "Preference != null && ServiceRate.Any(Carrier == @0)";
var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, bwc.Preference.Carrier).Compile();
bool res = expression(bwc); // true
bwc.ServiceRate.First().Carrier = "test1"; // just for testing this -> there is only one so I've used first
res = expression(bwc); // false

答案 1 :(得分:0)

您想使用属于BestWayContext的Preference,但您没有告诉编译器。如果我在Linq上写下你的表达,我将按如下方式进行:

[BestWayContext列表]。其中(f =&gt; f.Preference!= null&amp;&amp; f.ServiceRate.Where(g =&gt; g.Carrier == f.Preference.Carrier) );

如您所见,我指定使用BestWayContext的首选项。