How to write a generic sort extension

This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

  • Do you intend to make list elements generic? Like this:

    public static class ObjectExtension
    {
        public static List<T> Sort<T>(this List<T> list) where T : IFoo
        {
            list.Sort((x, y) => string.Compare(x.Name, y.Name));
            return list;
        }
    }
    
    public interface IFoo {
        string Name { get; }
    }
    
    public class Foo1 {
        public string Name { get; set; }
    }
    
    public class Foo2 {
        public string Name { get; set; }
    }
    

    Your parameter should be the collection of your type, so you'll be able to treat it as a collection, and access the Name property:

    public static class ObjectExtension
    {
        public static List<Foo> MyGenericSortFunction(this List<Foo> list)
        {
            list.Sort((x, y) => string.Compare(x.Name, y.Name));
            return list;
        }
    }
    

    You wouldn't use a generic here because you specifically need to use Name , which is a property of your Foo class. If it was defined in an interface, you could make your extension generic to the interface.

    Note that this edits the existing list, rather than returning a new list like LINQ would do.

    链接地址: http://www.djcxy.com/p/70956.html

    上一篇: C#列表逻辑失败

    下一篇: 如何编写一个通用的排序扩展