C#顺序列表由两个不同的东西组成

时间:2011-07-07 06:57:13

标签: c# list .net-4.0

假设我有以下列表:

var someList = new List<SomeObject>();

其中包含以下条目:

SomeObject.Field

Apple
Orange
FruitBowl_Outside
Banana
Grape
FruitBowl_Inside

我想对此列表进行排序,以便FruitBowl条目位于底部,受此约束,所有内容都是按字母顺序排列的。

用词来说:

SomeObject.Field

Apple
Banana
Grape
Orange
FruitBowl_Inside
FruitBowl_Outside

5 个答案:

答案 0 :(得分:9)

您可以使用OrderBy()ThenBy()方法:

var orderedList = someList.OrderBy(obj => obj.Field.StartsWith("FruitBowl_"))
                          .ThenBy(obj => obj.Field);

答案 1 :(得分:2)

您可以创建自己的IComparer并将其传递给List.Sort方法。我将很快发布代码。

        List<Record> list = new List<Record>();
        list.Add(new Record("Apple"));
         list.Add(new Record("Orange"));
        list.Add(new Record("FruitBowl_Outside"));
        list.Add(new Record("Banana"));
        list.Add(new Record("Grape"));
        list.Add(new Record("FruitBowl_Inside"));
        list.Sort(new RecordComparer());



public class Record {
    public Record(string data) {
        this.data = data;
    }
    private string data;
    public string Data {
        get { return data; }
        set {
            data = value;
        }
    }
}


public class RecordComparer : IComparer<Record> {
    public int Compare(Record x, Record y) {
        if(x.Data.Contains("FruitBowl") && !y.Data.Contains("FruitBowl"))
            return 1;
        if(y.Data.Contains("FruitBowl") && !x.Data.Contains("FruitBowl"))
            return -1;
        return x.Data.CompareTo(y.Data);
    }
}

答案 2 :(得分:1)

怎么样:

someList.OrderBy(a => a.Field.StartsWith("FruitBowl")).ThenBy(a => a.Field);

答案 3 :(得分:0)

您可以将List.Sort()与自定义比较方法一起使用 - 请参阅HERE

答案 4 :(得分:0)

这个怎么样↓

someList.Sort(new Comparison<string>((x, y) => { return x.StartsWith("FruitBowl") ^ y.StartsWith("FruitBowl") ? (x.StartsWith("FruitBowl") ? 1 : -1) : x.CompareTo(y); }));

使用样本↓

static void Main(string[] args)
    {
        List<string> lstData = new List<string>()
        {
            "Apple",
            "Orange",
            "FruitBowl_Outside",
            "Banana",
            "Grape",
            "FruitBowl_Inside"
        };


        lstData.Sort(new Comparison<string>((x, y) => { return x.StartsWith("FruitBowl") ^ y.StartsWith("FruitBowl") ? (x.StartsWith("FruitBowl") ? 1 : -1) : x.CompareTo(y); }));


        foreach (string data in lstData)
            Console.WriteLine(data);

        Console.ReadLine();
    }