Link to home
Start Free TrialLog in
Avatar of NewtonianB
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);
SOLUTION
Avatar of Stephan_Schrandt
Stephan_Schrandt
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of NewtonianB
NewtonianB

ASKER

Hi wdosanjos:
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?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Obadiah Christopher
SortedList?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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());

        }
    }
}

Open in new window