我在我的项目中使用List<T>
,此列表包含数百个条目。我使用的List.Contains方法相当多,这会损害性能,我用字典替换了List,但导致内存瓶颈,从而使性能甚至更糟。有没有更好的解决方案,可以建议在List中搜索?在C#2.0中是否有替代HashSet<T>
或其他方式更好的内存和速度?C#2.0中的HashSet替换
7
A
回答
0
如果您能满足安装.Net 3.5框架的要求,您可以在2.0项目中使用.NET 3.5(System.Core.dll)中的HashSet。
看到这个问题:Using HashSet in C# 2.0, compatible with 3.5
如果这是一个没有去,我会用字典来代替。
6
A Dictionary<T,bool>
可用于代替HashSet<T>
。无论您添加值为True还是False的项目都是抛硬币,价值无关。
它比HashSet<T>
更笨重,不是很轻,但它肯定比List<T>
好。
3
public class HashCollection <T> : ICollection <T>
{
private Dictionary<T, bool> _innerDictionary;
public HashCollection()
{
_innerDictionary = new Dictionary<T, bool>();
}
void ICollection <T>.Add(T item)
{
AddInternal(item);
}
private void AddInternal(T item)
{
_innerDictionary.Add(item, false);
}
public bool Add(T item)
{
if (_innerDictionary.ContainsKey(item))
return false;
AddInternal(item);
return true;
}
public void Clear()
{
_innerDictionary.Clear();
_innerDictionary = new Dictionary<T, bool>();
}
public bool Contains(T item)
{
return _innerDictionary.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_innerDictionary.Keys.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _innerDictionary.Keys.Count; }
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool Remove(T item)
{
return _innerDictionary.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return _innerDictionary.Keys.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
+0
这对我来说很好!谢谢! – Smartis 2016-07-01 09:22:31
相关问题
- 1. AesCryptoServiceProvider替换.Net 2.0中的
- 2. .NET 4 ISet <> HashSet <>替换NHibernate Iesi.Collections ISet,HashSet?
- 3. HashSet中的HashSet c#元素修改
- 4. 转义或替换XSLT 2.0中的值
- 5. 替换字符串中的字符串列表(Objective-c 2.0)
- 6. 将C#HashSet转换为F#集
- 7. C#hashSet的列表
- 8. HashSet相等c#
- 9. c中的宏替换#
- 10. c#中的XML替换
- 11. C中的变量替换
- 12. 在HashSet中使用替代比较
- 13. C#HashSet Equals方法
- 14. BYTE C宏的C++替换
- 15. 在C#中替换并替换为Java中的所有
- 16. c C中的互斥锁替换
- 17. 如何在运行时替换Objective-C 2.0类方法
- 18. C#替换String.Split
- 19. 如何将Invoke-RestMethod替换为PowerShell 2.0
- 20. 学说2.0 entitymanager->替换()等效
- 21. 在C#中使用“\ /”替换“\”#
- 22. 在C++中替换函数
- 23. 在C#中,替换 “\\” 到 “\”
- 24. 在C中替换字符#
- 25. 在CakePHP的2.0替换AppController中的其他名字
- 26. XSLT 2.0,替换函数:如何用大写替换匹配的组?
- 27. 如何用Silverlight 2.0 Combobox中的mouseover替换click事件?
- 28. 如何通过REST API 2.0替换WordPress中的图片?
- 29. C - 替换单词
- 30. c#替换整数
你想做什么?列表限制是什么?您尚未提供建议需要基于的那种信息。 – Oded 2011-05-12 12:14:44
列表 Iam使用,和List.Contains复杂性是O(N),所以它是伤害性能。 –
2011-05-12 12:24:54
你在这个列表中持有什么样的数据?数以百计的参赛作品并不多。无论如何,你没有解释你在列表中做什么。说'包含'意味着什么。 – Oded 2011-05-12 12:26:08