91

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

4

7 回答 7

114

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

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

于 2009-05-28T01:17:44.437 回答
26

你可以看看做这样的事情

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);   
于 2009-05-28T03:04:38.807 回答
14

我不确定这是否算得上一个好的答案,但是当需要一个保持插入顺序的唯一集合时,我并排使用了 HashSet 和 List 妥协。在这种情况下,每当您添加到集合中时,请执行以下操作:

if(hashSet.Add(item))
    orderList.Add(item);

删除项目时,请确保将它们从两者中删除。因此,只要您可以确定没有其他任何项目添加到列表中,您将拥有一个按插入排序的唯一集!

于 2012-06-13T09:28:07.727 回答
13

您还可以使用 Linq,如下所示:

using System.Linq;

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

List<string> distinctItems = items.Distinct().ToList();
于 2018-01-02T14:10:46.013 回答
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
于 2014-02-21T08:56:32.297 回答
2

This is not part of the the system namespace but have used the Iesi.Collections from http://www.codeproject.com/KB/recipes/sets.aspx with NHibernate. It has support for hashed set along with sorted set, dictionary set, and so on. Since it has been used with NHibernate it has been used extensively and very stable. This also does not require .Net 3.5

于 2009-05-28T01:42:24.637 回答
2

这是另一个不使用HashSet.

var items = new List<string>() { "one", "one", "two", "one", "two", "zero" };
var uniqueItems = items.Where((item, index) => items.IndexOf(item) == index);

它是从这个线程中采用的:javascript - 数组中的唯一值

测试:

using FluentAssertions;

uniqueItems.Count().Should().Be(3);
uniqueItems.Should().BeEquivalentTo("one", "two", "zero");

List的性能测试。100 万次迭代:HashSetSortedSet

List: 564 ms
HashSet: 487 ms
SortedSet: 1932 ms

测试源代码(要点)

于 2016-08-04T10:55:29.627 回答