Anonymous IComparer implementation

前端 未结 8 1080
一整个雨季
一整个雨季 2021-02-03 17:57

Is it possible to define an anonymous implementation of IComparer?

I believe Java allows anonymous classes to be defined inline - does C#?

Looking at this code I

8条回答
  •  耶瑟儿~
    2021-02-03 18:05

    C# does not allow implementing interfaces using anonymous inner classes inline, unlike Java. For simple comparisons (i.e. comparing on a single key), there is a better way to do this in C#. You can simply use the .OrderBy() method and pass in a lambda expression specifying the key.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    
    namespace Test{
        public class Test{
            public static void Main(){
                IList mylist = new List();
                for(int i=0; i<10; i++) mylist.Add(i);
                var sorted = mylist.OrderBy( x => -x );
                foreach(int x in sorted)
                    Console.WriteLine(x);
            }
        }
    }
    

提交回复
热议问题