How can I convert List<object> to Hashtable in C#?

后端 未结 4 1533
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 16:12

I have a list of objects, each containing an Id, Code and Description.

I need to convert this list into a Hashtable, using Description as the key an

相关标签:
4条回答
  • 2021-01-01 16:43
    theList.ForEach(delegate(theObject obj) { dic.Add(obj.Id, obj.Description); });
    
    0 讨论(0)
  • 2021-01-01 16:54

    Let's assume that your List contains objects of type Foo (with an int Id and a string Description).

    You can use Linq to turn that list into a Dictionary like this:

    var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);
    
    0 讨论(0)
  • 2021-01-01 16:56

    Also look at the System.Collections.ObjectModel.KeyedCollection<TKey, TItem>. It seems like a better match for what you want to do.

    0 讨论(0)
  • 2021-01-01 17:04

    If you have access to Linq, you can use the ToDictionary function.

    0 讨论(0)
提交回复
热议问题