【问题标题】:C# Linq Where Clause on Nested List Attribute嵌套列表属性上的 C# Linq Where 子句
【发布时间】:2015-05-06 11:08:16
【问题描述】:

我有一个类Proforma,其中包含一个MonthlyPayment 类型的列表。代码如下:

public class Proforma 
{
    List<MonthlyPayment> lstMonthlyPayment = new List<MonthlyPayment>();
    // Other Attributes
}

List<Proforma> lstProforma = Fetch();

现在我想从lstProforma 中选择那些记录,其中lstMonthlyPayment.Month==DateTime.Now.Month

我怎样才能做到这一点?

【问题讨论】:

  • 为什么不将MonthlyPayment.Month 存储为DateTime 并在需要时使用Month 属性或在需要时使用Year 属性?但是,不要将其存储为字符串,如果您存储诸如 Feburary 之类的拼写错误,则更是如此。
  • 因为每月付款也包含其他属性
  • 没问题,然后也使用其他属性。但我认为你没有明白我的意思。 Month 是一个字符串属性,但它更好地存储日期时间。
  • 是的,你说得对,它实际上是整数,我将编辑我的问题

标签: c# linq where-clause


【解决方案1】:

您可以使用以下 linq 查询:

 var query = from proforma in lstProforma
             from payment in proforma.lstMonthlyPayment
             where payment.Month == DateTime.Now.Month
             select proforma;

正如 Tim 在他的 comment 中指出的那样,您不应该为 Month 使用字符串,因为您的代码可能容易出现问题和拼写错误。您应该使用 DateTime 属性(Date 例如在 MonthlyPayment 类中)或整数。

【讨论】:

  • 据我所知,您的回答是正确的。我只是想指出,OP 正在寻找列表中包含 Month="Feburary" 而不是 "February" 的记录。属性 Month 应该是 intDateTime 但不是字符串。否则,它会出现本地化问题和拼写错误。
  • 哦,我现在明白了。好吧,不清楚他的 Month 数据结构是什么,所以我认为它是一个字符串。感谢您指出,虽然我还没有考虑过本地化问题
  • 我们如何将结果放入 List ? (我是 LINQ 的新手)
  • @MuhammadFaisal: query.ToList()
猜你喜欢
  • 2021-07-05
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多