Solved

sort array list of structure (key value)

Posted on 2011-02-21
7
365 Views
Last Modified: 2012-05-11
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);
0
Comment
Question by:NewtonianB
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 9

Assisted Solution

by:Stephan_Schrandt
Stephan_Schrandt earned 50 total points
ID: 34948262
You can use a custom comparer. Here's a good article on that: http://devcity.net/articles/20/1/20020304.aspx
0
 
LVL 23

Accepted Solution

by:
wdosanjos earned 350 total points
ID: 34948629
Does the following work for you?

public class MyClass
{
	public string key { get; set; }
	public string value { get; set; }
}

void Main()
{
	List<MyClass> myList = new List<MyClass>();
	
	myList.Add(new MyClass(){key="XYZ", value="Test 3"});
	myList.Add(new MyClass(){key="ABC", value="Test 1"});
	myList.Add(new MyClass(){key="DEF", value="Test 2"});
	myList.Add(new MyClass(){key="ABC", value="Test 1"});
	
	List<MyClass> orderedList = myList.OrderBy(i => i.key).ToList();
	
	foreach (var item in orderedList)
	{
		Console.WriteLine("key={0}, value={1}", item.key, item.value);
	}
}

Open in new window


Output:
key=ABC, value=Test 1
key=ABC, value=Test 1
key=DEF, value=Test 2
key=XYZ, value=Test 3

Open in new window

0
 

Author Comment

by:NewtonianB
ID: 34948760
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?
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 23

Assisted Solution

by:wdosanjos
wdosanjos earned 350 total points
ID: 34948841
It uses the generic version of List (List<MyClass>), then it uses Linq Extensions to do the sorting (.OrderBy).

The sample only sorts by 'key', if you need to sort by 'value' also the statement should be:

List<MyClass> orderedList = myList.OrderBy(i => i.key).ThenBy(i => i.value).ToList();

More Linq samples: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

I hope this helps.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 34949032
SortedList?
0
 
LVL 13

Assisted Solution

by:Naman Goel
Naman Goel earned 100 total points
ID: 34950016
Please refer to following code

here I am using MyObject in ArrayList and MyObjectComparer will be our comparer class.

0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 34950059
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

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Building an object from several other objects 4 40
Help with viewing image in ReportViewer 14 32
Put File 6 38
C# LINQ query question 11 33
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question