在Key / Value集合中使用List <t>的最佳方法是什么?</t>

时间:2009-01-06 13:12:40

标签: .net .net-3.5 collections dictionary

在键/值情况下保留集合对象(示例中为List)的最佳方法是什么,其中键是ID,值是T类型的集合?

这是唯一的选择还是在.NET 3.5中有更好的解决方案/另一个集合?

var x = new Dictionary<int, List<type>>();

6 个答案:

答案 0 :(得分:3)

这是一个很好的解决方案,并且可以很好地工作 - 您实际上正在使用{key = int,value = 4 byte reference}的字典对象。

当您通过键检索值时,您将返回对堆上List<T>的引用并能够使用它。对于您明显的问题,这将是一个非常有效和紧凑的解决方案。

答案 1 :(得分:0)

我不知道这是否是你所需要的,但我会斩首。

public Dictionary<int,List<T>> myFunction<T>()
{
    var returnvalue = new Dictionary<int,List<T>>();
    //Do some stuff with the collection.
    return returnvalue;
}

然后你可以打电话

public void Main()
{
  var functionreturn = myFunction<String>();
}

我不确定这是否会对您有所帮助,但它可能会帮助您重新提出问题。

注意:以上是空气编码,未经测试。

答案 2 :(得分:0)

我认为框架内没有任何内容,但我认为PowerCollections库中有一个MultiDictionary集合。你可以试试。

答案 3 :(得分:0)

我认为您应该根据自己的需要编写包装类。我的意思是,如果你需要存储预制列表的字典,Dictionary<int, List<type>>应该没问题,只要它只是一个私人财产。你不应该公开公开它,因为很明显它暴露了太多的信息,你不能把它投射到IDictionary<int, IList<T>>或类似的东西,因为缺乏协方差。

你最好的选择是这样的:

class MyWrapper<T>()
{
    private Dictionary<int, List<T>> dictionary { get; set; }
    public MyWrapper() { dictionary = new Dictionary<int, List<T>>(); }

    // Adds a new item to the collection
    public void Add(int key, T item)
    {
       List<T> list = null;
       if (!dictionary.TryGetValue(key, out list))
       {
          // If dictionary does not contain the key, we need to create a new list
          list = new List<T>();
          dictionary.Add(key, list);
       }
       list.Add(item);
    }

    public IEnumerable<T> this[int key]     
    {
       get
       {
           List<T> list = null;
           // We just return an empty list if the key is not found
           if (!dictionary.TryGetValue(key, out list)) return new List<T>();
           else return list;
       }
    }
}

显然,您的需求可能不同,您可能需要实现几个接口等,但这是一般的想法。

答案 4 :(得分:0)

如果您的ID是您的类型的成员,则可以考虑实施System.Collections.ObjectModel.KeyedCollection<TKey, TItem>

答案 5 :(得分:0)

您是否正在寻找一个多值字典,即一个键控集合,其中每个键可以有多个值? PowerCollections有这样一个MultiDictionary。