DooDoo
DooDoo

Reputation: 13437

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 HashTable, and I want to specify Key and Value in Extension Method Argument. For example I may want to Key=Id and Value=Index or Key = Id + Index and Value = Name + LName. How can I do this?

Upvotes: 6

Views: 18067

Answers (7)

cuongle
cuongle

Reputation: 75296

You can use 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 don't need to use Hashtable which comes from .NET 1.1, Dictionary is more type-safe.

Upvotes: 12

D J
D J

Reputation: 7028

using ForEach.

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

Upvotes: -1

daryal
daryal

Reputation: 14919

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

Upvotes: 1

Parimal Raj
Parimal Raj

Reputation: 20565

Finally the 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);
    }

Upvotes: 1

dzendras
dzendras

Reputation: 4751

You can use LINQ to convert the list to generic Dictionary, which is far better than raw HashTable:

List<tmp> list = GetSomeData();
var dictionary = list.ToDictionary(entity => entity.Id);

Upvotes: 0

tukaef
tukaef

Reputation: 9214

In C# 4.0 you can use Dictionary<TKey, TValue>:

var dict = lst.ToDictionary(x => x.Id + x.Index, x => x.Name + x.LName);

But if you really want a Hashtable, pass that dictionary as a parameter in HashTable constructor...

var hashTable = new Hashtable(dict);

Upvotes: 6

sloth
sloth

Reputation: 101032

You can use the ToDictionary extension method and pass the resulting Dictionary to the Hashtable constructor:

var result = new Hashtable(lst.ToDictionary(e=>e.Id, e=>e.Index));

Upvotes: 3

Related Questions