Reputation: 2673
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.
Upvotes: 5
Views: 767
Reputation: 75306
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());
Upvotes: 4
Reputation: 41757
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);
Upvotes: 8