2011-05-12 79 views
7

我在我的项目中使用List<T>,此列表包含数百个条目。我使用的List.Contains方法相当多,这会损害性能,我用字典替换了List,但导致内存瓶颈,从而使性能甚至更糟。有没有更好的解决方案,可以建议在List中搜索?在C#2.0中是否有替代HashSet<T>或其他方式更好的内存和速度?C#2.0中的HashSet替换

+0

你想做什么?列表限制是什么?您尚未提供建议需要基于的那种信息。 – Oded 2011-05-12 12:14:44

+0

列表 Iam使用,和List.Contains复杂性是O(N),所以它是伤害性能。 – 2011-05-12 12:24:54

+0

你在这个列表中持有什么样的数据?数以百计的参赛作品并不多。无论如何,你没有解释你在列表中做什么。说'包含'意味着什么。 – Oded 2011-05-12 12:26:08

回答

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