.net core LINQ根据某个字段的特定值排序前置

今天遇到一个要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();
        }

       
    }
}

posted @ 2021-04-22 23:27  沐雪架构师  阅读(449)  评论(0编辑  收藏  举报