加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ:显示空列表的结果

发布时间:2020-12-15 06:28:21 所属栏目:百科 来源:网络整理
导读:我在C#中创建了两个实体(简化): class Log { entries = new ListEntry(); DateTime Date { get; set; } IListEntry entries { get; set; } } class Entry { DateTime ClockIn { get; set; } DateTime ClockOut { get; set; } } 我使用以下代码初始化对象:
我在C#中创建了两个实体(简化):
class Log {  
    entries = new List<Entry>();

    DateTime Date { get; set; }  
    IList<Entry> entries { get; set; }  
}  

class Entry {  
    DateTime ClockIn { get; set; }  
    DateTime ClockOut { get; set; }  
}

我使用以下代码初始化对象:

Log log1 = new Log() {
    Date = new DateTime(2010,1,1),};
log1.Entries.Add(new Entry() {
    ClockIn = new DateTime(0001,9,0),ClockOut = new DateTime(0001,12,0)
});

Log log2 = new Log()
{
    Date = new DateTime(2010,2,};

以下方法用于获取日期日志:

var query =  
    from l in DB.GetLogs()
    from e in l.Entries  
    orderby l.Date ascending  
    select new  
    {  
        Date = l.Date,ClockIn = e.ClockIn,ClockOut = e.ClockOut,};

上面的LINQ查询的结果是:

/*
 Date        | Clock In   | Clock Out
 01/01/2010  | 09:00      | 12:00    
*/

我的问题是,重写上面的LINQ查询以包含我创建的第二个对象(Log2)的结果的最佳方法是什么,因为它有一个空列表.换句话说,我想显示所有日期,即使它们没有时间值.

预期结果将是:

/*
 Date        | Clock In   | Clock Out
 01/01/2010  | 09:00      | 12:00    
 02/01/2010  |            |            
*/

解决方法

试试这个:
var query =  
    from l in DB.GetLogs()
    from e in l.Entries.DefaultIfEmpty()
    orderby l.Date ascending  
    select new  
    {  
        Date = l.Date,ClockIn = e == null ? null : e.ClockIn,ClockOut = e == null ? null : e.ClockOut,};

有关它的更多信息,请参见docs for DefaultIfEmpty.

编辑:您可能只想更改它以执行内存中的最后部分:

var dbQuery =  
    from l in DB.GetLogs()
    from e in l.Entries.DefaultIfEmpty()
    orderby l.Date ascending  
    select new { Date = l.Date,Entry = e };

var query = dbQuery.AsEnumerable()
                   .Select(x => new { 
                        Date = x.Date,ClockIn = x.Entry == null ? null : x.Entry.CLockIn,ClockOut = x.Entry == null ? null : x.Entry.CLockOut
                    });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读