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

#引言

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

#代码:

1     public class Foo
2     {
3         public int Id { get; set; }
4         public string Name { get; set; }
5     }

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

 1    List<Foo> foos = new List<Foo> {
 2        new Foo { Id = 1, Name = "b" }, new Foo { Id = 2, Name = "a" },
 3        new Foo { Id = 3, Name = "A" }, new Foo { Id = 4, Name = "B" }
 4    };
 5    int[] orderArr = new int[]{4,2,3,1};
 6    foos = foos.OrderBy(e =>
 7    {
 8        var index = 0;
 9        index = Array.IndexOf(orderArr, e.Id);
10        if (index != -1) { return index; }
11        else
12        {
13            return int.MaxValue;
14        }
15 
16    }).ToList();
17 
18    foos.ForEach(p =>
19    {
20        Console.WriteLine(string.Format("Id:{0},Name:{1}",p.Id,p.Name));
21    });

 

——————————————————————————————————————————————————————————————————

posted @ 2019-04-29 17:18  willingtolove  阅读(9019)  评论(0编辑  收藏  举报