【问题标题】:Use Linq and lambda to flatten a list使用 Linq 和 lambda 来展平列表
【发布时间】:2010-07-28 11:36:38
【问题描述】:

我有课。

public class MedicalRequest
{
    private int id
    private IList<MedicalDays> Days 
    private string MedicalUser
    ...
}

还有一个

public class MedicalDays
{
    private int id;
    private DateTime? day
    private MedicalRequest request
    ...
}

我有 MedicalUser,所以我可以选择一个

IList<MedicalRequest> reqList = dao.FindAll(example);

此时我希望能够做的是将 MedicalDays 列表展平并返回 DateTime 日期。

类似

IList<DateTime> dateList = reqList.SelectMany(i => i.MedicalDays.day);

有人可以推动我朝着正确的方向前进吗?

感谢您的宝贵时间。

【问题讨论】:

    标签: c# linq nhibernate lambda extension-methods


    【解决方案1】:

    你快到了:

    IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays)
                                             .Select(m => m.day);
    

    或者:

    IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays,
                                                         (i, m) => m.day);
    
    • 如果您需要 IList&lt;T&gt; 而不是 IEnumerable&lt;T&gt;,您可以在结果上调用 ToList()
    • 如果您需要使用DateTime 而不是DateTime?,您可以像这样过滤掉空天:

      IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays)
                                               .Select(m => m.day)
                                               .Where(x => x.HasValue)
                                               .Select(x => x.Value);
      

    【讨论】:

    • 谢谢乔恩,一如既往地很有帮助。
    【解决方案2】:
    IEnumerable<DateTime> dateList = reqList.SelectMany(i => i.MedicalDays)
                                            .Select(i => i.day);
    

    【讨论】:

    • 感谢您的回复本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多