将List<T>转换为HashTable

6

我有一个列表:

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

List<tmp> lst = GetSomeData();

我希望将此列表转换为哈希表,并且我想在扩展方法参数中指定KeyValue。例如,我可能想要Key=IdValue=IndexKey=Id+IndexValue=Name+LName。我该如何做到这一点?

https://dev59.com/iW3Xa4cB1Zd3GeqPgZrh#14496667 - Parimal Raj
2
你是否因为遗留原因(例如使用某些第三方或旧代码)而使用HashTable?如果不是,像其他评论者建议的那样,改用Dictionary<TKey,TValue>。 - Matthew Watson
@AppDeveloper 这绝对是我第一次看到有人在问题的评论中链接他们的答案。 - JWiley
7个回答

12
您可以使用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 的 HashtableDictionary 更加类型安全。


6
在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);

3
你可以使用 ToDictionary 扩展方法,然后将生成的 Dictionary 传递给 Hashtable 构造函数。
var result = new Hashtable(lst.ToDictionary(e=>e.Id, e=>e.Index));

1
这个很好用,但显然它会为字典数据创建一个额外的副本 - 对于大型数据集来说可能是个问题。幸运的是,使用接受 IDictionary 作为参数的 Hashtable 构造函数只需要 O(N) 的操作 - 但即使如此,如果你直接填充 Hashtable,可以避免这种情况。一如既往,如果速度是一个问题,可以使用 Stopwatch 来计时以查看差异是否显著。 - Matthew Watson

1

最后是非Linq的方法

    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
作为扩展方法,将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;
    }
}

0
你可以使用LINQ将列表转换为泛型字典,这比原始的HashTable要好得多。
List<tmp> list = GetSomeData();
var dictionary = list.ToDictionary(entity => entity.Id);

-1

使用 ForEach。

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

你能给出一个不实用的原因吗? - D J
你可以逐一删除列表中的所有项目,也可以直接调用 Clear 方法。你能看到相似之处吗?最好的代码是你没有编写过的那个。 - dzendras
添加和删除是完全不同的。但是你有没有看到这里我们不需要字典作为中间结构。如果我们使用字典,我们会将项目添加两次,一次在字典中,一次在哈希表中。如果数据量很大,你不觉得这会影响性能吗? - D J

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接