Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> to HashTable

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?

like image 837
Arian Avatar asked Jan 24 '13 08:01

Arian


People also ask

How to Convert list to Hashtable in c#?

You can use ToDictionary method: var dic1 = list. ToDictionary(item => item.Id, item => item.Name); var dic2 = list. ToDictionary(item => item.Id + item.

Is Hashtable faster than dictionary C#?

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.

Is Hashtable faster than dictionary?

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.


2 Answers

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.

like image 190
cuongle Avatar answered Sep 24 '22 23:09

cuongle


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);
like image 29
tukaef Avatar answered Sep 22 '22 23:09

tukaef