列出<string>复杂排序</string>

时间:2012-12-11 16:24:17

标签: c# linq sorting lambda arraylist

我有List<string>个尺码,比如XS,S,M,L,XL,XXL,UK 10,UK 12等

我想要的是强制订单成为上述订单,无论列表中的项目顺序如何,我认为我需要一个IComparable运算符但不确定。

理想情况下,我想让另一个List具有正确的顺序,它可以在列表中引用它的'place'并重新排序,如果它不存在则默认为A-Z

5 个答案:

答案 0 :(得分:18)

按照您希望它们的顺序创建一个尺寸数组,然后根据它们在该数组中的尺寸位置对衬衫进行排序:

string[] sizes = new [] {"XS", "S", "M", "L", "XL", "XXL", "UK 10", "UK 12"};

var shirtsInOrder = shirts
                        .OrderBy(s=>sizes.Contains(s) ? "0" : "1")  // put unmatched sizes at the end
                        .ThenBy(s=>Array.IndexOf(sizes,s))  // sort matches by size
                        .ThenBy(s=>s); // sort rest A-Z

答案 1 :(得分:3)

var order = new string[] { "XS", "S", "M", "L", "XL", "XXL", "UK10", "UK12" };

var orderDict = order.Select((c, i) => new { sze = c, ord = i })
            .ToDictionary(o => o.sze, o => o.ord);

var list = new List<string> { "S", "L", "XL", "L", "L", "XS", "XL" };
var result = list.OrderBy(item => orderDict[item]);

答案 2 :(得分:2)

您可以直接使用OrderByDescending + ThenByDescending

sizes.OrderByDescending(s => s == "XS")
     .ThenByDescending( s => s == "S")
     .ThenByDescending( s => s == "M")
     .ThenByDescending( s => s == "L")
     .ThenByDescending( s => s == "XL")
     .ThenByDescending( s => s == "XXL")
     .ThenByDescending( s => s == "UK 10")
     .ThenByDescending( s => s == "UK 12")
     .ThenBy(s => s);

我使用...Descending,因为true类似于1而false为0。

答案 3 :(得分:0)

您还可以创建其他列表,并使用委托与排序一起使用,如果索引为size1&gt;则返回size2的索引。

答案 4 :(得分:0)

您也可以这样做:

public class ShirtComparer : IComparer<string>
{
    private static readonly string[] Order = new[] { "XS", "S", "M", "L", "XL", "XXL", "UK10", "UK12" };

    public int Compare(string x, string y)
    {
        var xIndex = Array.IndexOf(Order, x);
        var yIndex = Array.IndexOf(Order, y);

        if (xIndex == -1 || yIndex == -1) 
            return string.Compare(x, y, StringComparison.Ordinal);

        return xIndex - yIndex;
    }
}

用法:

var list = new List<string> { "S", "L", "XL", "L", "L", "XS", "XL", "XXXL", "XMLS", "XXL", "AM19" };
var result = list.OrderBy(size => size, new ShirtComparer());

对于不在列表中的值,它也应该默认为A-Z ...