0

If I have the arrays:

var list1 = new int[] { 1,2,3,4,5};
var list2 = new int[] { 1,2,3};
var list3 = new int[] { 2,3};

what method can help me keep only value found on all the lists. In this example I will like to end up with {2,3} because those two values are found on all the lists.

4

4 回答 4

4

使用Intersect-> 通过使用默认相等比较器比较值来生成两个序列的集合交集。(MSDN:http: //msdn.microsoft.com/en-us/library/bb460136.aspx

var list = list1.Intersect(list2).Intersect(list3);
于 2013-10-28T18:26:13.837 回答
3

您可以使用此方法获取任意数量序列的交集:

public static IEnumerable<T> IntersectAll<T>(params IEnumerable<T>[] sequences)
{
    if (!sequences.Any())
        return Enumerable.Empty<T>();

    var set = new HashSet<T>(sequences.First());
    foreach (var sequence in sequences.Skip(1))
    {
        set.IntersectWith(sequence);
    }
    return set;
}

请注意,与重复调用 LINQIntersect方法不同,这不会重复重建中间HashSet. 它将自始至终重复使用同一个。

于 2013-10-28T18:29:50.700 回答
1

您可以使用作为 LINQ 一部分的 Intersect 方法,如下所示:

var result = list1.Intersect(list2).Intersect(list3);

如果你想要一个可以传递任意数量列表的方法,你可以使用这个:

public static int[] Process(params int[][] values)
{
    int[] result = values[0];

    foreach (int[] value in values)
    {
        result = result.Intersect(value).ToArray();
    }

    return result;
}

你可以这样称呼它:

var result = Process(list1, list2, list3);
于 2013-10-28T18:27:40.583 回答
0

其他人已经提出了良好且可行的解决方案。根据他们的回答,我提出了这个:

 public static class IEnumerableExtension
    {
        public static IEnumerable<T> Intersect<T>(this IEnumerable<T> one, params IEnumerable<T>[] others)
        {
            var result = one;
            foreach (var other in others)
                result = result.Intersect(other);

            return result;
        }
    }

用法将是这样的:

var result = list1.Intersect(list2,list3,...continued to...listn);
于 2013-10-28T18:35:43.550 回答