15
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5

2番目のリストにも存在する1つのリストからすべての要素を取得する方法は?

この場合は次のようになります: 1, 4

もちろん、foreach を使用しないメソッドについても話します。むしろlinqクエリ

4

2 に答える 2

51

Intersectメソッドを使用できます。

var result = one.Intersect(second);

例:

void Main()
{
    List<int> one = new List<int>() {1, 3, 4, 6, 7};
    List<int> second = new List<int>() {1, 2, 4, 5};

    foreach(int r in one.Intersect(second))
        Console.WriteLine(r);
}

出力:

1
4

于 2012-07-31T12:24:49.497 に答える
4
static void Main(string[] args)
        {
            List<int> one = new List<int>() { 1, 3, 4, 6, 7 };
            List<int> second = new List<int>() { 1, 2, 4, 5 };

            var result = one.Intersect(second);

            if (result.Count() > 0)
                result.ToList().ForEach(t => Console.WriteLine(t));
            else
                Console.WriteLine("No elements is common!");

            Console.ReadLine();
        }
于 2012-07-31T13:28:10.760 に答える