Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

IEnumerable.Joinメソッド

Enumerable.Join(TOuter, TInner, TKey, TResult) メソッド (IEnumerable(TOuter), IEnumerable(TInner), Func(TOuter, TKey), Func(TInner, TKey), Func(TOuter, TInner, TResult)) (System.Linq)
一致するキーに基づいて 2 つのシーケンスの要素を相互に関連付けます。 キーの比較には既定の等値比較子が使用されます。

SQLでは、INNER JOINに相当します。

ソースコード

using System;
using System.Linq;

namespace LinqSample {
    class Program {
        static void Main(string[] args) {
            Man[] mans = new Man[] { 
                new Man() { Name = "suzuki taro", Age = 20 },
                new Man() { Name = "sato taro", Age = 21 },
                new Man() { Name = "sato jiro", Age = 20 }
            };

            Pet[] pets = new Pet[] {
                new Pet() { Name = "dog", Owner = "sato jiro" },
                new Pet() { Name = "cat", Owner = "sato taro" },
                new Pet() { Name = "horse", Owner = "suzuki taro" }

            };

            var q = mans.Join(
                pets, 
                man => man.Name,    // JOINのキー
                pet => pet.Owner,   // JOINのキー
                (man, pet) => new { Name = man.Name, Pet = pet.Name });

            foreach (var obj in q) {
                Console.WriteLine("Man = {0}, Pet = {1}", obj.Name, obj.Pet);
            }

            Console.ReadKey();
        }
    }

    class Man {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Pet {
        public string Name { get; set; }
        public string Owner { get; set; }
    }
}

実行結果