sherebiah.tishbi
sherebiah.tishbi

Reputation: 17

Generic Sorting

I have a many entities and and I want to write some generic sorting class which can provide me a sorted list on a given object and a property. e.g.

Class Country
{
      public int id { get; set; }
      public string CountryName { get; set; }
}

Now I should be able to pass unsorted List to my sorter class along with property name on which it should be sorted. I have beat myself quite a while by now and got stuck now. Any help will be appreciated.

Upvotes: 0

Views: 221

Answers (4)

sherebiah.tishbi
sherebiah.tishbi

Reputation: 17

Finally I was able to implement the generic sorter and also makign that as an extension method so I can use it anywhere where I use List, below is my implementation. sortorder is Asc/Desc and propertyname is the name of property of type T. This works fine and I am happy with this.

public static List<T> SortedListWithLamda<T>(this List<T> list, string sortorder, string propertyname)
        {
            List<T> sortedlist = new List<T>();
            if (!string.IsNullOrEmpty(propertyname) && list != null && list.Count > 0)
            {

                Type t = list[0].GetType();

                if (sortorder == "A")
                {

                    sortedlist = list.OrderBy(
                        a => t.InvokeMember(
                            propertyname
                            , BindingFlags.GetProperty
                            , null
                            , a
                            , null
                        )
                    ).ToList();
                }
                else
                {
                    sortedlist = list.OrderByDescending(
                        a => t.InvokeMember(
                            propertyname
                            , BindingFlags.GetProperty
                            , null
                            , a
                            , null
                        )
                    ).ToList();
                }
            }
            return sortedlist;
        }

Upvotes: 0

Richard
Richard

Reputation: 8280

Sorting by a property name can be easily achieved using .NET LINQ extension methods, or more specifically, the Dynamic LINQ section. Take a look at Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) written by Scott Gu regarding how it all works. Essentially your sorter class needn't be anything more than a fancy wrapper for the LINQ extension OrderBy and OrderByDescending.

Here's an example:

var sortedCountries = listOfCountries.OrderBy("CountryName");

Alternatively, if you're familiar with generics, you could write a wrapper that accepts a collection, and a Func<TSource, TKey> used to select the properties value, like so:

public class MySorterClass
{
    public IEnumerable<TSource> OrderList<TSource, TKey>(IEnumerable<TSource> list, Func<TSource, TKey> selector)
    {
        return list.OrderBy(selector);
    }

    public IEnumerable<TSource> OrderList<TSource>(IEnumerable<TSource> list, string propertyName)
    {
        return list.OrderBy(propertyName);
    }
}

Upvotes: 1

LeeNeverGup
LeeNeverGup

Reputation: 1114

Workaround:

You didn't mention a language. In c# you can make your classes implement the interface IComparable and add CompareTo function, which take two args and return which one bigger, or use anonymous function that do the same.

Upvotes: 0

John Kane
John Kane

Reputation: 4443

If you are using Java, take a look at Collections.Sort(...). There are two versions, one I think uses that natural ordering of your elements to sort them (take a look at the Compareable) interface, the other takes in a Comparator. Either should work. Otherwise I am sure other languages have something very similar.

Upvotes: 0

Related Questions