C# linq sort - quick way of instantiating IComparer

后端 未结 5 1244
遥遥无期
遥遥无期 2021-02-01 03:42

When using linq and you have

c.Sort()

Is there any good inline way of defining a Comparison and/or IComparer class w

5条回答
  •  醉梦人生
    2021-02-01 03:51

    Jon's answer is great but can be a little bit out of date, with release of .NET 4.5 we now (finally!) have this awesome method Comparer.Create

    items.Sort((x, y) => x.Value.CompareTo(y.Value)); //sorting List                
    items.OrderBy(x => x, Comparer.Create((x, y) => x.Value.CompareTo(y.Value))); //sorting IEnumerable
    

    Assuming Item is defined something like:

    class Item
    {
        public readonly int Key;
        public readonly string Value;
    
        public Item(int key, string value)
        {
            Key = key;
            Value = value;
        }
    }
    

提交回复
热议问题