【C#】List按指定字段的给出的自定义顺序进行排序

#引言

有一个集合,对其进行排序,排序规则为:按对象中某个字段的特定顺序进行排序,比如:对象属性id,按照【4,2,5,1】的顺序排序;

#代码:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

1、demo1:按字段id进行自定义排序

   List<Foo> foos = new List<Foo> {
       new Foo { Id = 1, Name = "b" }, new Foo { Id = 2, Name = "a" },
       new Foo { Id = 3, Name = "A" }, new Foo { Id = 4, Name = "B" }
   };
   int[] orderArr = new int[]{4,2,3,1};
   foos = foos.OrderBy(e =>
   {
       var index = 0;
       index = Array.IndexOf(orderArr, e.Id);
       if (index != -1) { return index; }
       else
       {
           return int.MaxValue;
       }

   }).ToList();

   foos.ForEach(p =>
   {
       Console.WriteLine(string.Format("Id:{0},Name:{1}",p.Id,p.Name));
   });

*原文地址:https://www.cnblogs.com/willingtolove/p/10791655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值