Using IComparer comparer

1. How to order a sequence using custom comparer?

 

Example 1:

            var orders = from c in Data.Customers

                                from o in c.Orders

                                orderby o.Month

                                select o;

Output:

20 – True – December – 3

20 – True – December – 3

3 – False – January – 1

10 – False – July – 1

20 – False – July – 5

20 – False – July – 5

5 – True – May – 2

 

Example 2:

 

public class MonthComparer : IComparer<string>

{

       

            #region IComparer<string> Members

            public int Compare(string x, string y)

            {

                IFormatProvider provider = new CultureInfo("en-us");

 

                DateTime xMonth = DateTime.ParseExact(x, "MMMM", provider);

                DateTime yMonth = DateTime.ParseExact(y, "MMMM", provider);

 

                return DateTime.Compare(xMonth, yMonth);

            }

            #endregion

}

 

            var orderedOrders = Data.Customers

                            .SelectMany(o => o.Orders)

                            .OrderBy(order => order.Month, new MonthComparer());

Output:

3 – False – January – 1

5 – True – May – 2

10 – False – July – 1

20 – False – July – 5

20 – False – July – 5

20 – True – December – 3

20 – True – December – 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s