LINQ GroupJoin, Join

  • 299
  • 0

摘要:LINQ GroupJoin, Join

有 log檔不定時產生,想列表查看哪幾天有,哪幾天沒有;很像 SQL裡的 outer join,趁機會用用極不熟的 LINQ JOIN。


    class log
    {
        public string date { get; set; }
        public string data { get; set; }
    }

List data = new List
{
    new log { date = "2015-07-24", data = "test1" },
    new log { date = "2015-07-21", data = "test2" },
    new log { date = "2015-07-14", data = "test3" },
    new log { date = "2015-07-14", data = "test4" },
};
var allDays = Enumerable.Range(0, 10)
    .Select(offset => DateTime.Parse("2015-07-24").AddDays(offset * -2).ToString("yyyy-MM-dd"))
    .OrderBy(r => r).ToList();

var fullJoin = allDays.GroupJoin(
    data,
    allDay => allDay,
    log => log.date,
    (allDay, log) => new { allDay, log }
);//.SelectMany(r => r.log.DefaultIfEmpty(), (l, r) => r);

var join = allDays.Join(
    data,
    allDay => allDay,
    log => log.date,
    (allDay, log) => new { allDay, log }
);

var dataJoin = data.GroupJoin(
    allDays,
    log => log.date,
    allday => allday,
    (log, day) => new { log, inDay = day.Count() > 0 }
);

foreach (var item in fullJoin)
{
    Console.WriteLine(JsonConvert.SerializeObject(item)); // log會被包成 IEnumerable,要解開這層取得原始型態可用 SelectMany
}
Console.WriteLine("======================================");
foreach (var item in join)
{
    Console.WriteLine(JsonConvert.SerializeObject(item));
}
Console.WriteLine("======================================");
foreach (var item in dataJoin)
{
    Console.WriteLine(JsonConvert.SerializeObject(item));
}

結果:


{"allDay":"2015-07-06","log":[]}
{"allDay":"2015-07-08","log":[]}
{"allDay":"2015-07-10","log":[]}
{"allDay":"2015-07-12","log":[]}
{"allDay":"2015-07-14","log":[{"date":"2015-07-14","data":"test3"},{"date":"2015-07-14","data":"test4"}]}
{"allDay":"2015-07-16","log":[]}
{"allDay":"2015-07-18","log":[]}
{"allDay":"2015-07-20","log":[]}
{"allDay":"2015-07-22","log":[]}
{"allDay":"2015-07-24","log":[{"date":"2015-07-24","data":"test1"}]}
======================================
{"allDay":"2015-07-14","log":{"date":"2015-07-14","data":"test3"}}
{"allDay":"2015-07-14","log":{"date":"2015-07-14","data":"test4"}}
{"allDay":"2015-07-24","log":{"date":"2015-07-24","data":"test1"}}
======================================
{"log":{"date":"2015-07-24","data":"test1"},"inDay":true}
{"log":{"date":"2015-07-21","data":"test2"},"inDay":false}
{"log":{"date":"2015-07-14","data":"test3"},"inDay":true}
{"log":{"date":"2015-07-14","data":"test4"},"inDay":true}