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.
Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function.
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.
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.
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With