I have a list:
public class tmp
{
public int Id;
public string Name;
public string LName;
public decimal Index;
}
List<tmp> lst = GetSomeData();
I want to convert this list to HashTable, and I want to specify Key
and Value
in Extension Method Argument. For example I may want to Key=Id
and Value=Index
or Key = Id + Index
and Value = Name + LName
. How can I do this?
You can use ToDictionary method: var dic1 = list. ToDictionary(item => item.Id, item => item.Name); var dic2 = list. ToDictionary(item => item.Id + item.
In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value. The data retrieval is slower than Dictionary due to boxing/ unboxing. The data retrieval is faster than Hashtable due to no boxing/ unboxing.
Dictionary is a generic type and returns an error if you try to find a key which is not there. The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.
You can use ToDictionary
method:
var dic1 = list.ToDictionary(item => item.Id,
item => item.Name);
var dic2 = list.ToDictionary(item => item.Id + item.Index,
item => item.Name + item.LName);
You don't need to use Hashtable
which comes from .NET 1.1, Dictionary
is more type-safe.
In C# 4.0 you can use Dictionary<TKey, TValue>
:
var dict = lst.ToDictionary(x => x.Id + x.Index, x => x.Name + x.LName);
But if you really want a Hashtable
, pass that dictionary as a parameter in HashTable
constructor...
var hashTable = new Hashtable(dict);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With