Andre
Andre

Reputation: 820

Sort ArrayList of hashtables based on key within each hashtable

Let's say I have an ArrayList with a collection of hashtables as items - something like this:

Hashtable ht1 = new Hashtable();
ht1.add('position', 1);
ht1.add('trending', 2);

Hashtable ht2 = new Hashtable();
ht2.add('position', 2);
ht2.add('trending', 1);

...more of these with varying position & trending values

ArrayList arr = new ArrayList();
arr.add(h1);
arr.add(h2);
...

initially the array is sorted by "position" and i print out the info with a simple loop

for(int x=0; x < arr.length; x++)
{
    Hashtable h = (Hashtable)arr[x];
    print(h["position"]);
}

next, i want to re-order the array by the "trending" and loop again.

is this possible to sort the array based on keys within each hashtable item?

Upvotes: 1

Views: 2049

Answers (3)

L.B
L.B

Reputation: 116138

public class AClass
{
    public int Position { set; get; }
    public int Trending { set; get; }
}

List<AClass> list = new List<AClass>() ;

list.Add(new AClass() { Position = 1, Trending = 2 });
list.Add(new AClass() { Position = 2, Trending = 1 });

var order1 = list.OrderBy(x => x.Position).ToArray();
foreach (var item in order1)
{
    Console.WriteLine(item.Position);
}

var order2 = list.OrderBy(x => x.Trending).ToArray();
foreach (var item in order2)
{
    Console.WriteLine(item.Position);
}

Upvotes: 2

user287466
user287466

Reputation:

If you're stuck with 1.1, you'll want something like this;

class MyComparer : IComparer
{
    string key;
    public MyComparer(string key)
    {
        this.key = key;
    }
    public int Compare(object x, object y)
    {
        return ((int)((Hashtable)x)[key]).CompareTo((int)((Hashtable)y)[key]);
    }
}

then you can call arr.Sort(new MyComparer("trending"));

When someone posts a solution using generics you'll see how much cleaner it is.

Upvotes: 2

trembon
trembon

Reputation: 768

if you are willing to change it

create a class of the values you store in the hashtable

public class Item{
   public int Position { get; set; }
   public int Trending { get; set; }
}

create some instances of these classes in a generic list instead of ArrayList

List<Item> items = new List<Item>();
items.Add(new Item{ Position = 1, Trending = 2 });
items.Add(new Item{ Position = 2, Trending = 1 });

then you use lambda to sort the list

List<Item> listOrderByPosition = items.OrderBy(i => i.Position).ToList();
List<Item> listOrderByTrending = items.OrderBy(i => i.Trending).ToList();

Upvotes: 0

Related Questions