How do I use the IComparable interface?

后端 未结 6 408
后悔当初
后悔当初 2021-02-02 13:40

I need a basic example of how to use the IComparable interface so that I can sort in ascending or descending order and by different fields of the object type I\'m s

6条回答
  •  梦毁少年i
    2021-02-02 13:59

    Well, since you are using List it would be a lot simpler to just use a Comparison, for example:

    List data = ...
    // sort by name descending
    data.Sort((x,y) => -x.Name.CompareTo(y.Name));
    

    Of course, with LINQ you could just use:

    var ordered = data.OrderByDescending(x=>x.Name);
    

    But you can re-introduce this in List (for in-place re-ordering) quite easily; Here's an example that allows Sort on List with lambda syntax:

    using System;
    using System.Collections.Generic;  
    
    class Foo { // formatted for vertical space
        public string Bar{get;set;}
    }
    static class Program {
        static void Main() {
            List data = new List {
                new Foo {Bar = "abc"}, new Foo {Bar = "jkl"},
                new Foo {Bar = "def"}, new Foo {Bar = "ghi"}
            };
            data.SortDescending(x => x.Bar);
            foreach (var row in data) {
                Console.WriteLine(row.Bar);
            }
        }
    
        static void Sort(this List source,
                Func selector) {
            var comparer = Comparer.Default;
            source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
        }
        static void SortDescending(this List source,
                Func selector) {
            var comparer = Comparer.Default;
            source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
        }
    }
    

提交回复
热议问题