避免将重复元素添加到列表 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14433332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:47:38  来源:igfitidea点击:

Avoid Adding duplicate elements to a List C#

c#asp.netasp.net-mvclistc#-4.0

提问by vini

string[] lines3 = new string[100];
List<string> lines2 = new List<string>();
lines3 = Regex.Split(s1, @"\s*,\s*");

if (!lines2.Contains(lines3.ToString()))
{
    lines2.AddRange(lines3.Distinct().ToArray());
}

I have checked all the spaces etc but i still get duplicate values in my lines2 List

我已经检查了所有空格等,但我的行 2 中仍然有重复的值 List

I have to remove my duplicate values here itself

我必须在这里删除我的重复值本身

采纳答案by Habib

Your this check:

你的这张支票:

if (!lines2.Contains(lines3.ToString()))

is invalid. You are checking if your lines2contains System.String[]since lines3.ToString()will give you that. You need to check if item from lines3exists in lines2or not.

是无效的。您正在检查,如果你的lines2包含System.String[],因为lines3.ToString()会给你的。您需要检查项目中是否lines3存在lines2

You can iterate each item in lines3check if it exists in the lines2and then add it. Something like.

您可以迭代每个项目以lines3检查它是否存在于 中lines2,然后添加它。就像是。

foreach (string str in lines3)
{
    if (!lines2.Contains(str))
        lines2.Add(str);
}

Or if your lines2is any empty list, then you can simply add the lines3distinct values to the list like:

或者,如果您lines2是任何空列表,那么您可以简单地将lines3不同的值添加到列表中,例如:

lines2.AddRange(lines3.Distinct());

then your lines2will contain distinct values.

那么您lines2将包含不同的值。

回答by Ian Mercer

If you don't want duplicates in a list, use a HashSet. That way it will be clear to anyone else reading your code what your intention was and you'll have less code to write since HashSetalready handles what you are trying to do.

如果您不希望列表中有重复项,请使用HashSet. 这样,其他任何阅读您代码的人都会清楚您的意图是什么,并且您将编写更少的代码,因为HashSet已经处理了您正在尝试做的事情。

回答by Guffa

If your check would have worked, it would have either added all the items, or none at all. However, calling the ToStringmethod on an array returns the name of the data type, not the contents of the array, and the Containsmethod can only look for a single item, not a collection of items anyway.

如果您的支票有效,它要么添加所有项目,要么根本不添加。但是,ToString在数组上调用该方法返回的是数据类型的名称,而不是数组的内容,并且该Contains方法只能查找单个项,而无论如何都不能查找项的集合。

You have to check each string in the array:

您必须检查数组中的每个字符串:

string[] lines3;
List<string> lines2 = new List<string>();

lines3 = Regex.Split(s1, @"\s*,\s*");

foreach (string s in lines3) {
  if (!lines2.Contains(s)) {
    lines2.Add(s);
  }
}

However, if you start with an empty list, you can use the Distinctmethod to remove the duplicates, and you only need a single line of code:

但是,如果您从一个空列表开始,则可以使用该Distinct方法删除重复项,并且只需要一行代码:

List<string> lines2 = Regex.Split(s1, @"\s*,\s*").Distinct().ToList();

回答by Sergey Berezovskiy

You can use Enumerable.Exceptto get distinct items from lines3 which is not in lines2:

您可以使用Enumerable.Except从第 3 行中获取不在第 2 行中的不同项目:

lines2.AddRange(lines3.Except(lines2));

If lines2 contains all items from lines3 then nothing will be added. BTW internally Except uses Set<string>to get distinct items from second sequence and to verify those items present in first sequence. So, it's pretty fast.

如果lines2 包含lines3 中的所有项目,则不会添加任何内容。顺便说一句,Except 内部用于Set<string>从第二个序列中获取不同的项目并验证第一个序列中存在的那些项目。所以,速度相当快。

回答by Tieson T.

You could use a simple Union+ Distinct:

您可以使用简单的Union+ Distinct

var lines = lines2.Union(lines3).Distinct();

That will add all the items from the second list into the first list, and then return all the unique strings in the combined list. Not likely to perform well with large lists, but it's simple.

这会将第二个列表中的所有项目添加到第一个列表中,然后返回组合列表中的所有唯一字符串。不太可能在大型列表中表现良好,但这很简单。

Reference: http://msdn.microsoft.com/en-us/library/bb341731.aspx

参考:http: //msdn.microsoft.com/en-us/library/bb341731.aspx

回答by Erxin

If you want to save distinct values into a collection you could try HashSet Class. It will automatically remove the duplicate values and save your coding time. :)

如果要将不同的值保存到集合中,可以尝试HashSet Class。它将自动删除重复值并节省您的编码时间。:)

回答by danvasiloiu

use HashSetit's better

使用HashSet它更好

take a look here : http://www.dotnetperls.com/hashset

看看这里:http: //www.dotnetperls.com/hashset

回答by Felipe Oriani

Use a HashSet<string>instead of a List<string>. It is prepared to perform a better performance because you don't need to provide checks for any items. The collection will manage it for you. That is the difference between a listand a set. For sample:

使用 aHashSet<string>代替 a List<string>。它准备好执行更好的性能,因为您不需要为任何项目提供检查。该集合将为您管理它。这就是 alist和 a之间的区别set。样品:

HashSet<string> set = new HashSet<string>();

set.Add("a");
set.Add("a");
set.Add("b");
set.Add("c");
set.Add("b");
set.Add("c");
set.Add("a");
set.Add("d");
set.Add("e");
set.Add("e");

var total = set.Count;

Total is 5and the values are a, b, c, d, e.

总计是5,值是abcde

The implemention of List<T>does not give you nativelly. You can do it, but you have to provide this control. For sample, this extension method:

的实现List<T>本身并没有给你。你可以做到,但你必须提供这种控制。例如,这个extension method

public static class CollectionExtensions
{
    public static void AddItem<T>(this List<T> list, T item)
    {
       if (!list.Contains(item))
       {
          list.Add(item);
       }
    }
}

and use it:

并使用它:

var list = new List<string>();
list.AddItem(1);
list.AddItem(2);
list.AddItem(3);
list.AddItem(2);
list.AddItem(4);
list.AddItem(5);

回答by Ph?m Tu?n Anh

Use a HashSetalong with your List:

将 aHashSet与您的List:

List<string> myList = new List<string>();
HashSet<string> myHashSet = new HashSet<string>();

public void addToList(string s) {
    if (myHashSet.Add(s)) {
        myList.Add(s);
    }
}

myHashSet.Add(s)will return trueif sis not exist in it.

myHashSet.Add(s)true如果s不存在,将返回。

回答by Amir Javed

not a good way but kind of quick fix, take a bool to check if in whole list there is any duplicate entry.

不是一个好方法,而是一种快速修复,使用 bool 检查整个列表中是否有任何重复条目。

bool containsKey;
string newKey;

    public void addKey(string newKey){

         foreach(string key in MyKeys){
           if(key == newKey){
             containsKey = true;
          }
         }

      if(!containsKey){
       MyKeys.add(newKey);
     }else{
       containsKey = false;
     }

    }