简体   繁体   English

C#中的排序列表

[英]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. 提前致谢。

LINQ has just the methods for this. LINQ只有这方面的方法。

Try the following to order by matches with the fewest StoreIds first and then to sub order by matches with the most OrderLineIds: 尝试使用以下内容来匹配最少StoreIds的匹配,然后通过匹配最多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: 或者通过匹配最多的OrderLineIds排序,然后通过与最少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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM