简体   繁体   中英

C# order list by two different things

Let's say I have the following list:

var someList = new List<SomeObject>();

Which has the following entries:

SomeObject.Field

Apple
Orange
FruitBowl_Outside
Banana
Grape
FruitBowl_Inside

I would like to sort this list so that FruitBowl entries go at the bottom, and that subject to this, everything is alphabetic.

In order words:

SomeObject.Field

Apple
Banana
Grape
Orange
FruitBowl_Inside
FruitBowl_Outside

You can use the OrderBy() and ThenBy() methods:

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

You can create your own IComparer and pass it to the List.Sort method. I will post the code shortly.

        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);
    }
}

How about:

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

You can use List.Sort() with a custom compare method - see HERE .

how about this ↓

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

And with the sample ↓

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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