今天遇到一个要List要把某一个字段特定的一个值排到最前面的需求。
using System; using System.Collections.Generic; using System.Linq; namespace NetCoreConsoleApp1 { class Ad { public string a1 { get; set; } public int val { get; set; } = 0; public string toString() { return $"a1={a1},val={val}"; } } class Program { static void Main(string[] args) { List<Ad> ads = new List<Ad>(); ads.Add(new Ad() { a1 = "www.zyiz.net", val = 4 }); ads.Add(new Ad() { a1 = "www.uweixin.com", val=21 }); ads.Add(new Ad() { a1 = "找一找教程网", val = 11 }); ads.Add(new Ad() { a1 = "c", val = 1331 }); ads.Add(new Ad() { a1 = "www.chinasem.cn", val = 11 }); Console.WriteLine("排序前"); ads.ForEach(o => { Console.WriteLine(o.toString()); }); Console.WriteLine("排序后"); //将val==11的放最前 var ads1 = ads.OrderByDescending(o => o.val == 11).ToList(); ads1.ForEach(o => { Console.WriteLine(o.toString()); }); Console.ReadKey(); } } }