読者です 読者をやめる 読者になる 読者になる

LINQ で左外部結合

.net

いつも忘れて、その度ネットで調べているので、ブログにメモしておく。 DefaultIfEmpty を使うのがポイント。

using System;
using System.Linq;

namespace LinqLeftOuterJoinSample
{
    public class Sector
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int SectorId { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var sectors = new Sector[]
            {
                new Sector { Id = 1, Name = "営業部" },
                new Sector { Id = 2, Name = "開発部" },
            };
            var users = new User[]
            {
                new User { Id = 1, Name = "武藤", SectorId = 1 },
                new User { Id = 2, Name = "宇佐美" },
                new User { Id = 3, Name = "柴崎", SectorId = 2 },
                new User { Id = 4, Name = "本田", SectorId = 1 },
            };

            var result = from u in users
                         join s in sectors on u.SectorId equals s.Id into tmp
                         from s2 in tmp.DefaultIfEmpty()
                         select new
                         {
                             UserName = u.Name,
                             SectorName = (s2 != null) ? s2.Name : "未所属",
                         };

            foreach(var r in result)
            {
                Console.WriteLine($"{r.UserName}({r.SectorName})");
            }

            Console.ReadLine();
        }
    }
}