Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list in C#

I have a list of custom type. And the custom type is

public class PossibleMatch
    {
        public PossibleMatch()
        {
            StoreIds = new List<long>();
            OrderLineIds = new List<long>();
        }
        public IList<long> StoreIds { get; set; }
        public IList<long> OrderLineIds { get; set; }
    }

I have to sort the list in such a way item with less number of stores and more number of order lines should be at top.

Thanks in advance.

like image 332
Naresh Avatar asked Nov 02 '12 11:11

Naresh


People also ask

Is there a sorting function in C?

Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function.

Which is best sorting algorithm in C?

Quicksort. Quicksort is one of the most efficient sorting algorithms, and this makes of it one of the most used as well. The first thing to do is to select a pivot number, this number will separate the data, on its left are the numbers smaller than it and the greater numbers on the right.

What is a sorted list in programming?

The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index.


2 Answers

LINQ has just the methods for this.

Try the following to order by matches with the fewest StoreIds first and then to sub order by matches with the most OrderLineIds:

 var possibleMatches = new List<PossibleMatch>();
 var ordered = possibleMatches.OrderBy(pm => pm.StoreIds.Count).ThenByDesc(pm => pm.OrderLineIds.Count);

Or to order by matches with the most OrderLineIds first and then to sub order by matches with the fewest StoreIds:

var ordered = possibleMatches.OrderByDesc(pm => pm.OrderLineIds.Count).ThenBy(pm => pm.StoreIds.Count);
like image 161
Rich O'Kelly Avatar answered Sep 23 '22 02:09

Rich O'Kelly


Build Custom Comparer:

public class PossibleMatchComparer: IComparer<PossibleMatch>
{
    public int Compare(PossibleMatch x, PossibleMatch y)
    {
        if (x.StoreIds.Count < y.StoreIds.Count) return -1;
        if (x.StoreIds.Count > y.StoreIds.Count) return 1;

        return y.OrderLineIds.Count - x.OrderLineIds.Count;
    }
}

So you can use:

list.Sort(new PossibleMatchComparer());
like image 39
cuongle Avatar answered Sep 23 '22 02:09

cuongle