高效的唯一字符串列表C#

84 c# unique-values

存储忽略任何重复的字符串列表的最有效方法是什么?我在想字典可能是最好通过编写dict [str] = false来插入字符串; 并通过键枚举列表.这是一个好的解决方案吗?

JP *_*oto 107

如果您使用的是.NET 3.5,则HashSet应该适合您.

HashSet <(Of <(T>)>)类提供高性能集合操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.

  • 但是`HashSet`会丢失项目的顺序."List"提供的功能. (5认同)
  • 附加:还有SortedSet <T>这是一个方便的排序HashSet. (4认同)

Per*_*der 22

你可以做这样的事情

var hash = new HashSet<string>();
var collectionWithDup = new []{"one","one","two","one","two","zero"}; 

// No need to check for duplicates as the Add method
// will only add it if it doesn't exist already
foreach (var str in collectionWithDup)
    hash.Add(str);   
Run Code Online (Sandbox Code Playgroud)

  • 您不需要使用HashSet进行包含检查.您可以直接调用Add方法,它将返回true或false,具体取决于该项是否已存在. (32认同)

sco*_*one 14

我不确定这是否算作一个好的答案,但是当面对需要一个维护插入顺序的唯一集时,我并没有与HashSet和List并列.在这种情况下,无论何时添加到集合,请执行以下操作:

if(hashSet.Add(item))
    orderList.Add(item);
Run Code Online (Sandbox Code Playgroud)

删除项目时,请务必从两者中删除它们.因此,只要您确定没有其他项目添加到列表中,您将拥有一个插入排序的唯一集合!


小智 9

您还可以按以下方式使用Linq:

using System.Linq;

var items = new List<string>() { "one", "one", "two", "one", "two", "zero" };

List<string> distinctItems = items.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)


小智 8

使用HashSet,无需检查.Contains(),只需在列表中添加项目,如果重复,则不会添加它.

   HashSet<int> uniqueList = new HashSet<int>();
   uniqueList.Add(1); // List has values 1
   uniqueList.Add(2);  // List has values 1,2
   uniqueList.Add(1);  // List has values 1,2
   Console.WriteLine(uniqueList.Count); // it will return 2
Run Code Online (Sandbox Code Playgroud)