使用复杂对象的C#Lambda表达式

时间:2015-08-31 22:38:19

标签: c# linq lambda visual-studio-2015

如何在具有List Payment对象的PaymentFields对象列表中使用Lambda表达式。这就是我现在所拥有的。

var list = paymentList.Where(payment => payment.PaymentFields.Any(field => field.FieldName == "ItemA" && field.FieldValue == "50");

这样我就可以将ItemA作为字段名称,将50作为字段值。但是,我想像这样比较两个PaymentField ...

Where FieldName == "ItemA" && FieldValue = "50" && FieldName ItemA < FieldName ItemB

我该怎么做?

我有两个对象:

public class Payment
{
    public int Id { set; get; }
    public string Name { set; get; }
    public List<PaymentFields> PaymentFields { set; get; }
}

public class PaymentFields
{
    public string FieldName { set; get; }
    public string FieldValue { set; get; }
}

以下是一个示例对象:

var payment = new Payment()
{
    Id = 1,
    Name = "Test",
    PaymentFields = new List<PaymentFields>()
    {
        new PaymentFields()
        {
            FieldName = "ItemA",
            FieldValue = "20"
         },
         new PaymentFields()
         {
             FieldName = "ItemB",
             FieldValue = "50"
          }
    }
};

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果您完全确定会有“ItemA”和“ItemB”,那么这将有效。

如果缺少“ItemA”或“ItemB”,则会抛出异常。

var list = paymentList
             .Where(payment => payment.PaymentFields.Any(field => field.FieldName == "ItemA" && field.FieldValue == "50")
             .Where(payment => payment.PaymentFields.First(field => field.FieldName == "ItemA").FieldValue
                                   <
                               payment.PaymentFields.First(field => field.FieldName == "ItemB").FieldValue)
                    );