我有一个清单:
public class tmp
{
public int Id;
public string Name;
public string LName;
public decimal Index;
}
List<tmp> lst = GetSomeData();
我想将此列表转换为HashTable,并且我想在Extension Method Argument中指定Key
和Value
。例如,我可能想要Key=Id
和Value=Index
或Key = Id + Index
和Value = Name + LName
。我怎样才能做到这一点?
答案 0 :(得分:11)
您可以使用ToDictionary
方法:
var dic1 = list.ToDictionary(item => item.Id,
item => item.Name);
var dic2 = list.ToDictionary(item => item.Id + item.Index,
item => item.Name + item.LName);
您不需要使用来自.NET 1.1的Hashtable
,Dictionary
更加类型安全。
答案 1 :(得分:5)
在C#4.0中,您可以使用Dictionary<TKey, TValue>
:
var dict = lst.ToDictionary(x => x.Id + x.Index, x => x.Name + x.LName);
但如果您真的想要Hashtable
,请将该字典作为HashTable
构造函数中的参数传递...
var hashTable = new Hashtable(dict);
答案 2 :(得分:3)
您可以使用ToDictionary
扩展方法并将生成的词典传递给Hashtable
构造函数:
var result = new Hashtable(lst.ToDictionary(e=>e.Id, e=>e.Index));
答案 3 :(得分:1)
最后是NON-Linq Way
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);
}
答案 4 :(得分:1)
作为一种扩展方法,将List<tmp>
转换为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;
}
}
答案 5 :(得分:0)
您可以使用LINQ将列表转换为通用词典,这比原始HashTable要好得多:
List<tmp> list = GetSomeData();
var dictionary = list.ToDictionary(entity => entity.Id);
答案 6 :(得分:-1)
使用ForEach。
List<tmp> lst = GetSomeData();
Hashtable myHashTable = new Hashtable();
lst.ForEach((item) => myHashTable.Add(item.Id + item.Index, item.Name + item.LName));