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
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
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
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
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