84 c# unique-values
存储忽略任何重复的字符串列表的最有效方法是什么?我在想字典可能是最好通过编写dict [str] = false来插入字符串; 并通过键枚举列表.这是一个好的解决方案吗?
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)
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)
| 归档时间: |
|
| 查看次数: |
66727 次 |
| 最近记录: |