Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Generic List

Tags:

c#

.net

generics

I want to sort a Generic List in Ascending Date order. (Framework v2)

Any suggestions?

like image 401
chrr Avatar asked Jan 22 '10 11:01

chrr


People also ask

How do I sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.

Is C# list ordered?

In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order.

How do you create a list in C sharp?

The following example shows how to create list and add elements. In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.


2 Answers

Upul and Wim said it all:
Use delegates:

new List<DateTime>().Sort(delegate(DateTime d1, DateTime d2) {
    return d1.CompareTo(d2);
});

Or if you have a class or something that holds that datetime:

new List<Nhonho>().Sort(delegate(Nhonho n1, Nhonho n2) {
    return n1.date.CompareTo(n2.date);
});

To make it lessening,

new List<Nhonho>().Sort(delegate(Nhonho n1, Nhonho n2) {
    return n2.date.CompareTo(n1.date);
});

Good luck.

like image 162
marcelo-ferraz Avatar answered Oct 04 '22 14:10

marcelo-ferraz


For this scenario I would suggest something quite similar but in my opinion a better way to solve this problem.

I would implement new classes that their only pourpouse is to have a particular sorting "strategy". For example; I would create "ProductNameComparer" and "ProductPriceComparer", these classes should implement IComparer interface, then I would only call the method sort passing these strategies as parameters. You may check the code I have just made to ilustrate my ponit;

public class ProductPriceComparer : IComparer<Product>
    {
        public int Compare(Product x, Product y)
        {
            if (x.Price > y.Price)
                return 1;
            
            if (x.Price < y.Price)
                return -1;

            return 0;
        }
    }

    public class ProductNameComparer : IComparer<Product>
    {
        public int Compare(Product x, Product y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

    public class Product
    {
        public Product(String name, Decimal price)
        {
            this.name = name;
            this.price = price;
        }

        private String name;
        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        private Decimal price;
        public Decimal Price
        {
            get { return price; }
            set { price = value; }
        }

        public override string ToString()
        {
            return Name + " ($"+ Price.ToString() + ")";
        }
    }

    static void Main(string[] args)
    {
        List<Product> products = new List<Product>();
        products.Add(new Product("Product Z", 45.98m));
        products.Add(new Product("Product D", 12.80m));
        products.Add(new Product("Product A", 25.19m));
        products.Add(new Product("Product B", 65.00m));
        products.Add(new Product("Product P", 5.14m));

        Console.WriteLine("PRODUCTS SORTED BY PRICE");
        products.Sort(new ProductPriceComparer());
        foreach (Product p in products)
            Console.WriteLine(p.ToString());

        Console.WriteLine("\n--------------------------------\n");

        Console.WriteLine("PRODUCTS SORTED BY NAME");
        products.Sort(new ProductNameComparer());
        foreach (Product p in products)
            Console.WriteLine(p.ToString());
    }

What we are supossed to get is:

PRODUCTS SORTED BY PRICE
Product P ($5,14)
Product D ($12,80)
Product A ($25,19)
Product Z ($45,98)
Product B ($65,00)

PRODUCTS SORTED BY NAME
Product A ($25,19)
Product B ($65,00)
Product D ($12,80)
Product P ($5,14)
Product Z ($45,98)

I think it will help.

like image 26
user256680 Avatar answered Oct 04 '22 14:10

user256680