将List <T>转换为HashTable

Ari*_*ian 6 c# linq extension-methods hashtable c#-4.0

我有一个清单:

public class tmp
{
    public int Id;
    public string Name;
    public string LName;
    public decimal Index;
}

List<tmp> lst = GetSomeData();
Run Code Online (Sandbox Code Playgroud)

我想这个列表转换为哈希表,我想指定KeyValue在扩展方法参数.例如,我可能要Key=IdValue=IndexKey = Id + IndexValue = Name + LName.我怎样才能做到这一点?

cuo*_*gle 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);
Run Code Online (Sandbox Code Playgroud)

您不需要使用Hashtable.NET 1.1中的Dictionary类型,更安全.


tuk*_*aef 6

在C#4.0中,您可以使用Dictionary<TKey, TValue>:

var dict = lst.ToDictionary(x => x.Id + x.Index, x => x.Name + x.LName);
Run Code Online (Sandbox Code Playgroud)

但是,如果你真的想要一个Hashtable,那么将该字典作为HashTable构造函数中的参数传递...

var hashTable = new Hashtable(dict);
Run Code Online (Sandbox Code Playgroud)