Rob*_*uch 28 c# list duplicates
我的C#程序从给定模式生成随机字符串.这些字符串存储在列表中.由于不允许重复,我这样做:
List<string> myList = new List<string>();
for (int i = 0; i < total; i++) {
string random_string = GetRandomString(pattern);
if (!myList.Contains(random_string)) myList.Add(random_string);
}
Run Code Online (Sandbox Code Playgroud)
你可以想象这适用于数百个条目.但我面临的情况是产生数百万字符串.并且每次添加的字符串检查重复项都会变得越来越慢.
有没有更快的方法来避免重复?
Ser*_*rvy 44
使用可以更有效地确定项目是否存在的数据结构,即a HashSet.无论集合中的项目数是多少,它都可以确定项目是否在常量时间内处于集合中.
如果您确实需要项目中的项目List,或者您需要生成的列表中的项目按生成顺序排列,那么您可以将数据存储在列表和哈希集中; 如果该项目当前不存在,则将该项目添加到两个集合中HashSet.
最简单的方法是使用它:
myList = myList.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
虽然这需要创建一次列表,然后创建一个新列表.更好的方法可能是提前生成发电机:
public IEnumerable<string> GetRandomStrings(int total, string pattern)
{
for (int i = 0; i < total; i++)
{
yield return GetRandomString(pattern);
}
}
...
myList = GetRandomStrings(total, pattern).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
当然,如果你不需要通过索引访问项目,你可以通过放弃ToList并使用一个来提高效率IEnumerable.
你可以使用HashSet<string>if命令并不重要:
HashSet<string> myHashSet = new HashSet<string>();
for (int i = 0; i < total; i++)
{
string random_string = GetRandomString(pattern);
myHashSet.Add(random_string);
}
Run Code Online (Sandbox Code Playgroud)
HashSet类提供高性能的集合操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.
或者如果订单很重要,我建议使用SortedSet(仅限.net 4.5)
| 归档时间: |
|
| 查看次数: |
41823 次 |
| 最近记录: |