【问题标题】:Add Range of items to list without duplication将项目范围添加到列表中而不重复
【发布时间】:2013-01-12 20:41:48
【问题描述】:

我有一个List 或List 或Strings,我需要使用AddRange() 函数向其中添加一组项目,但不要重复项目。

我使用了以下代码:

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());

但它不起作用。

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

【问题讨论】:

标签: c# list distinct addrange


【解决方案1】:

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();

【讨论】:

  • @SergeyS 这是一个随机(小)数。要计算哈希码,您不需要遍历整个列表,尤其是当列表很长时。
  • 视情况而定,也许有时它会工作得很好,但对于某些列表和数据结构,它就不是那么好:)
  • @SergeyS 你说的毫无根据。即使我把它写成return 0 也可以工作(只是性能很差)。
  • 我没有说'它不会工作'。我说'不会那么好'。并且这是在计算机科学的基础上说的;)毫无疑问,这完全是关于性能的。
  • @Tilak Take(5).Aggregate(23,.. 是什么?为什么是 5 值?为什么是 23 值?这是什么意思?
【解决方案2】:

尝试以下 LINQ 查询

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

【讨论】:

  • 尝试这种方法..它没有编译。即使我引用 System.Linq,似乎也无法识别“y.Intersect”部分。
  • 未编译使用 System.Linq,y.Intersect 无法识别。 无法将类型 IEnumerable 隐式转换为 bool
  • -1;不编译。未找到相交未找到扩展。确实使用过 System.Linq,尝试使用 IEnumerable 以及 IList 和 LIst
猜你喜欢
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 2013-06-14
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多