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

版权声明:欢迎转载,转载请注明出处! https://blog.csdn.net/willingtolove/article/details/89679537

#引言

有一个集合,对其进行排序,排序规则为:按对象中某个字段的特定顺序进行排序,比如:对象属性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

猜你喜欢

转载自blog.csdn.net/willingtolove/article/details/89679537
今日推荐