将项目范围添加到列表而不重复

时间:2013-01-12 20:41:49

标签: c# list distinct addrange

我有List List Strings,我需要使用AddRange()函数为其添加一组项目,但绝不会重复项目。< / p>

我使用了以下代码:

List<List<string>> eList = new List<List<string>>();
List<List<string>> mergedList = new List<List<string>>(); 

//
// some code here
//

mergedList.AddRange(eList.Where(x => !mergedList.Contains(x)).ToList());

然而它不起作用。

添加了所有重复的项目,我该如何解决?

2 个答案:

答案 0 :(得分:8)

<强> A)

如果您对重复的含义是两个列表包含相同顺序的相同元素,那么

List<List<string>> eList = new List<List<string>>();
eList.Add(new List<string>() { "a", "b" });
eList.Add(new List<string>() { "a", "c" });
eList.Add(new List<string>() { "a", "b" });


var mergedList = eList.Distinct(new ListComparer()).ToList();

public class ListComparer : IEqualityComparer<List<string>>
{
    public bool Equals(List<string> x, List<string> y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<string> obj)
    {
        return obj.Take(5).Aggregate(23,(sum,s)=> sum ^= s.GetHashCode());
    }
}

<强> B)

如果列表中元素的顺序不重要,那么

List<List<string>> eList = new List<List<string>>();
eList.Add(new List<string>() { "a", "b" }); <--
eList.Add(new List<string>() { "a", "c" });
eList.Add(new List<string>() { "b", "a" }); <--

var mergedList = eList.Select(x => new HashSet<string>(x))
                      .Distinct(HashSet<string>.CreateSetComparer()).ToList();

答案 1 :(得分:3)

尝试遵循LINQ查询

mergeList.AddRange( eList.Where (x => mergeList.Where ( y => y.Intersect(x)).Any()));