2017-01-17 12 views
5

私はN個の "人"のリストを持っています。人々は2つのプロパティ:IdNameを持っています。私はすべてのNリストに含まれる人を見つけたいと思っています。私はイドにマッチしたいだけです。以下はN個のリストの中の共通のオブジェクトを見つける

は私の出発点である:

List<People> result = new List<People>(); 

//I think I only need to find items in the first list that are in the others 
foreach (People person in peoplesList.First()) { 

    //then this is the start of iterating through the other full lists 
    foreach (List<People> list in peoplesList.Skip(1)) { 

     //Do I even need this? 

    } 
} 

私は中央部のまわりで私の頭をラップしようとして立ち往生しています。私は各リストにあるものだけをpeoplesList.Skip(1)から探しています。

答えて

4

数学的に言えば;あなたはあなたのすべてのリストの間に設定された交差点を探しています。幸いにも、LINQはInstersectメソッドを持っていますので、あなたのセットを反復的に交差させることができます。

List<List<People>> lists; //Initialize with your data 
IEnumerable<People> commonPeople = lists.First(); 
foreach (List<People> list in lists.Skip(1)) 
{ 
    commonPeople = commonPeople.Intersect(list); 
} 
//commonPeople is now an IEnumerable containing the intersection of all lists 

あなたはそのかなりくそ簡単なので、取り残さIEqualityComparerの実際の実装People

IEqualityComparer<People> comparer = new PeopleComparer(); 
... 
commonPeople = commonPeople.Intersect(list, comparer); 

ためIEqualityComparerを実装する必要があります取り組ん「ID」セレクタを取得します。

+0

ああ、私たちは既存のリストを各交差点に変更しています。ニース!ありがとう、私はこれを与えるでしょう –

+1

@DustinBreakey新しい 'List'(あなたは*できますが、それはもっと効率的ではありません)新しいIEnumerable'だから、あなたは' commonPeople'を終わり。 – BradleyDotNET

関連する問題