Hi All,
I have a problem in my windows application with C#.net.
I have around 50 Id and Name pairs and need to sort them after putting into a SortedList.
In my data, ID is not unique.
SortedList< object key, object value>
So I can't put ID in place of Key( Key must be unique in sortedlist).
I have created a class with Id and Name variables, passing the object in place of value, and some integer index
in place of key.
Now the Question is, how to sort the SortedList on ID.
Please me help out,
Thanks.

sorting a sortedlist
Boogeyman777
One of the constructors of the SortedList take a IComparer as an argument. You can use this to sort the list. Keep in mind if the icomparer returns a 0 you will get an error about adding a duplicate to the list. Hope this helps
using System;
using System.Collections;
using System.Text;
namespace SortList
{
class Program
{
static void Main(string[] args)
{
SortedList lst = new SortedList(new sortMyClass()) ;
MyClass cls1 = new MyClass();
cls1.ID = 1;
cls1.Name = "1";
MyClass cls2 = new MyClass();
cls2.ID = 2;
cls2.Name = "2";
MyClass cls3 = new MyClass();
cls3.ID = 1;
cls3.Name = "Bob";
lst.Add(cls1,cls1);
lst.Add(cls2,cls2);
lst.Add(cls3,cls3);
foreach (DictionaryEntry de in lst)
{
MyClass c = (MyClass)de.Value;
Console.WriteLine(c.ID + " " + c.Name);
}
}
static int SortID(MyClass x, MyClass y)
{
return x.ID.CompareTo(y.ID);
}
}
class MyClass
{
private int myID;
public int ID
{
get { return myID; }
set { myID = value; }
}
private string myName;
public string Name
{
get { return myName; }
set { myName = value; }
}
}
public class sortMyClass : IComparer
{
int IComparer.Compare(object a, object b)
{
MyClass c1 = (MyClass)a;
MyClass c2 = (MyClass)b;
if (c1.ID > c2.ID)
return 1;
if (c1.ID < c2.ID)
return -1;
else
return c1.Name.CompareTo(c2.Name);
}
}
}
Brian Schmidt
I have no experience with the sortedList. But i thought of other possibilities.
1) If you have all your data in a DataTable, you can very easy sort everything with da DataView.
2) If you created a class your own you can customize all the way by implementing the IBindingList Interface...
Kosmo007