私は a を持っておりdictionary<int, List<string>>
、各 int のすべてのリストを交差させたいと考えています。
どうすればそれを達成できますか?これは簡単なはずなのに、なぜかうまくいかない。
ありがとう。
リストのシーケンスを繰り返し、最初のリストを a に入れてから、HashSet
各サブシーケンス リストと交差させるのは簡単です。
public static IEnumerable<T> intersectAll<T>(IEnumerable<IEnumerable<T>> source)
{
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
return Enumerable.Empty<T>();
var set = new HashSet<T>(iterator.Current);
while (iterator.MoveNext())
set.IntersectWith(iterator.Current);
return set;
}
}
IntersectAll(dictionary.Values.Cast<IEnumerable<string>>())
これを使用して、交点を取得するように記述できます。
次のようなものを探していると思います。
List<string> TheIntersection = myDict.Select(x => x.Value).Aggregate((c, n) => c.Intersect(n)).ToList();
しばらく前にOPと同様の質問があり、最終的にSkeetのソリューションを使用しました(これはServyのソリューションに似ています)
public List<T> IntersectAll<T>(IEnumerable<IEnumerable<T>> lists)
{
HashSet<T> hashSet = null;
foreach (var list in lists)
{
if (hashSet == null)
hashSet = new HashSet<T>(list);
else
hashSet.IntersectWith(list);
}
return hashSet == null ? new List<T>() : hashSet.ToList();
}
次に、交差リストを取得できます...
var intersectedList = IntersectAll(myDictionary.Values);