6

リストがあります:

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

List<tmp> lst = GetSomeData();

このリストをHashTableに変換し、拡張メソッド引数にKeyandを指定したい。Valueたとえば、Key=IdandValue=IndexまたはKey = Id + Indexandが必要な場合がありValue = Name + LNameます。これどうやってするの?

4

7 に答える 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);

Hashtable.NET 1.1 に由来するものを使用する必要はなく、Dictionaryよりタイプ セーフです。

于 2013-01-24T08:11:24.250 に答える
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);
于 2013-01-24T08:11:11.793 に答える
3

ToDictionary拡張メソッドを使用して、結果の Dictionary をHashtableコンストラクターに渡すことができます。

var result = new Hashtable(lst.ToDictionary(e=>e.Id, e=>e.Index));
于 2013-01-24T08:10:51.593 に答える
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);
    }
于 2013-01-24T08:16:09.573 に答える
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;
    }
}
于 2013-01-24T08:19:14.567 に答える
0

LINQ を使用して、リストを一般的な Dictionary に変換できます。これは、生の HashTable よりもはるかに優れています。

List<tmp> list = GetSomeData();
var dictionary = list.ToDictionary(entity => entity.Id);
于 2013-01-24T08:11:15.603 に答える
-1

ForEach を使用します。

        List<tmp> lst = GetSomeData();
        Hashtable myHashTable = new Hashtable();
        lst.ForEach((item) => myHashTable.Add(item.Id + item.Index, item.Name + item.LName));
于 2013-01-24T08:25:38.633 に答える