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 a HashTable, and I want to specify Key and Value in the argument of the extension method. For example, I might want Key=Id and Value=Index or Key = Id + Index and Value = Name + LName . How can i do this?

+4
source share
7 answers

You can use the 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 do not need to use the Hashtable that comes with .NET 1.1, the Dictionary more type safe.

+9
source

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 this dictionary as a parameter in the Hashtable constructor ...

 var hashTable = new Hashtable(dict); 
+5
source

You can use the ToDictionary extension ToDictionary and pass the resulting dictionary to a Hashtable :

 var result = new Hashtable(lst.ToDictionary(e=>e.Id, e=>e.Index)); 
+3
source

Finally, the NON-Linq path

  private static void Main() { List<tmp> lst = new List<tmp>(); Dictionary<decimal, string> myDict = new Dictionary<decimal, string>(); foreach (tmp temp in lst) { myDict.Add(temp.Id + temp.Index, string.Format("{0}{1}", temp.Name, temp.LName)); } Hashtable table = new Hashtable(myDict); } 
+1
source

As an extension method, converting List<tmp> to Hashtable ;

 public static class tmpExtensions { public static System.Collections.Hashtable ToHashTable(this List<tmp> t, bool option) { if (t.Count < 1) return null; System.Collections.Hashtable hashTable = new System.Collections.Hashtable(); if (option) { t.ForEach(q => hashTable.Add(q.Id + q.Index,q.Name+q.LName)); } else { t.ForEach(q => hashTable.Add(q.Id,q.Index)); } return hashTable; } } 
+1
source

You can use LINQ to convert the list to a general dictionary, which is much better than the original HashTable:

 List<tmp> list = GetSomeData(); var dictionary = list.ToDictionary(entity => entity.Id); 
0
source

using ForEach.

  List<tmp> lst = GetSomeData(); Hashtable myHashTable = new Hashtable(); lst.ForEach((item) => myHashTable.Add(item.Id + item.Index, item.Name + item.LName)); 
-1
source

All Articles