NewtonianB
asked on
sort array list of structure (key value)
I have an Array list of a custom class which is essentially has two attributes Key and Va
public class myClass
{
public key { get; set; }
public value { get; set; }
}
ArrayList myList = new ArrayList();
myList is a list of myClass
How can I sort myList by Key?
I've been doing this below in the past the problem is i can't use it anymore because it doesn't handle the case of duplicate keys, i cant have two of same keys in dictionary.
loop and add to dictionary (Key, Value)
Then sort dictionary
Dictionary<string, string> sortedTypes = myList .OrderBy(i => i.Key).ToDictionary(i => i.Key,
i => i.Value);
public class myClass
{
public key { get; set; }
public value { get; set; }
}
ArrayList myList = new ArrayList();
myList is a list of myClass
How can I sort myList by Key?
I've been doing this below in the past the problem is i can't use it anymore because it doesn't handle the case of duplicate keys, i cant have two of same keys in dictionary.
loop and add to dictionary (Key, Value)
Then sort dictionary
Dictionary<string, string> sortedTypes = myList .OrderBy(i => i.Key).ToDictionary(i => i.Key,
i => i.Value);
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SortedList?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
code is here:
using System.Linq;
using System;
using System.Globalization;
using System.Threading;
using System.Collections;
namespace ConsoleApplication
{
public class MyObject
{
public string Key { get; set; }
public object Value { get; set; }
}
public class MyObjectComparer : IComparer
{
public int Compare(object x, object y)
{
return String.Compare((x as MyObject).Key, (y as MyObject).Key,false);
}
}
class Program
{
static void Main(string[] args)
{
ArrayList arrayList = new ArrayList(
new MyObject[]{
new MyObject { Key = "a1", Value= 1234 },
new MyObject { Key = "a2", Value= 1234 },
new MyObject { Key = "a1", Value= 1234 },
new MyObject { Key = "aa1", Value= 1234 },
new MyObject { Key = "ab1", Value= 1234 }
}
);
arrayList.Sort(new MyObjectComparer());
}
}
}
ASKER
The output is what I want but I won't be able to try it until tomorrow.
How does it work? How does it manage to sort by value also?