Question

I have a List where element is:

struct element { 
                double priority; 
                int value; 
               }

How can I implement my own comparer which allow me sort List by priority ? I try with SortredList... but it don't allow douplicated keys :(

Big thanks for help!

Was it helpful?

Solution

If you can't rely on C# 3 extensions or Lambdas then you can have your struct implement the IComparable interface, like so:

struct element : IComparable
{
    double priority;
    int value;
    public element(int val, double prio)
    {
        priority = prio;
        value = val;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // throws exception if type is wrong
        element other = (element)obj;
        return priority.CompareTo(other.priority);
    }

    #endregion
}

There are also a typesafe version of this interface, but the principle is the same

After you have that interface implemented on your struct or class, calling the Sort method on List<> will "just work"

static void Main(string[] args)
{
    Random r = new Random();
    List<element> myList = new List<element>();
    for (int i = 0; i < 10; i++)
        myList.Add(new element(r.Next(), r.NextDouble()));
    // List is now unsorted 
    myList.Sort();
    // List is now sorted by priority
    Console.ReadLine();
}

OTHER TIPS

Assuming C# 3 or later:

var sorted = MyList.OrderBy(e => e.priority);

You can perform an in-place sort by using the Sort overload that takes a Comparison<T> delegate:

yourList.Sort((x, y) => x.priority.CompareTo(y.priority));

For older versions of C# you'll need to swap out the lambda for old-school delegate syntax:

yourList.Sort(
    delegate(element x, element y) { return x.priority.CompareTo(y.priority); });

This depends on if you want to sort the list itself, or retrieve the values in sorted order (without changing the list).

To sort the list itself (supposing you have a List<element> called elements):

elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted

.NET 2.0 equivalent:

elements.Sort(
    delegate(element x, element y) {
        return x.priority.CompareTo(y.priority);
    }
);

To get the values in sorted order:

var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order

There's no LINQ equivalent in .NET 2.0, but you can write your own:

public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
    List<T> copy = new List<T>(source);
    copy.Sort(comparison);

    foreach (T item in copy)
        yield return item;
}

Usage:

Comparison<element> compareByPriority = delegate(element x, element y) {
    return x.priority.CompareTo(y.priority);
};

// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);

If you want to sort the list itself without creating a new instance, you can implement IComparer, then call List.Sort with an instance of your implementation

public class ElementComparer : IComparer<element>
{
    public int Compare(element x, element y)
    {
        throw new NotImplementedException();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top