コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】LINQのIntersect関数の引数にラムダ式を使えるようにする拡張メソッド

ソースコード

using System;
using System.Collections.Generic;
using System.Linq;

public static class IEnumerableExtensions
{
    private sealed class CommonSelector<T, TKey> : IEqualityComparer<T>
    {
        private Func<T, TKey> m_selector;
        
        public CommonSelector( Func<T, TKey> selector )
        {
            m_selector = selector;
        }
        
        public bool Equals( T x, T y )
        {
            return m_selector( x ).Equals( m_selector( y ) );
        }
        
        public int GetHashCode( T obj )
        {
            return m_selector( obj ).GetHashCode();
        }
    }
    
    public static IEnumerable<T> Intersect<T, TKey>( 
        this IEnumerable<T> source, 
        IEnumerable<T>      second, 
        Func<T, TKey>       selector 
    )
    {
        return source.Intersect( 
            second, 
            new CommonSelector<T, TKey>( selector ) 
        );
    }
}

使い方

public class Character
{
    public int    m_id  ;
    public string m_name;
}

...

var list   = new List<Character>();
var second = new List<Character>();
list.Intersect( second, c => c.m_name );

参考サイト様

neue cc - LinqとIEqualityComparerへの疑問