C# List常用操作

创建测试Model

    #region 测试Model
    public class TestModel
    {
        public int Id { get; set; }
        public String Name { get; set; }
        public decimal Score { get; set; }
    }
    #endregion

List对象集合根据某一属性排序

            #region List对象集合根据某一属性排序
            List<TestModel> orderList = new List<TestModel>();
            orderList.Add(new TestModel { Id = 3, Name = "U3", Score = 30 });
            orderList.Add(new TestModel { Id = 2, Name = "U2", Score = 20 });
            orderList.Add(new TestModel { Id = 4, Name = "U4", Score = 40 });
            orderList.Add(new TestModel { Id = 1, Name = "U1", Score = 10 });

            // 根据Id值升序排序
            orderList.Sort((x, y) =>
            {
                return (x.Id - y.Id);
            });
            #endregion

List对象集合根据某一属性去重

            #region  List对象集合根据某一属性去重
            List<TestModel> distinctList = new List<TestModel>();
            distinctList.Add(new TestModel { Id = 3, Name = "U3", Score = 30 });
            distinctList.Add(new TestModel { Id = 3, Name = "U2", Score = 20 });
            distinctList.Add(new TestModel { Id = 2, Name = "U4", Score = 40 });
            distinctList.Add(new TestModel { Id = 2, Name = "U1", Score = 10 });

            // 保留第一个元素去除其它Id一样的元素
            List<TestModel> distinctListById = distinctList.GroupBy(t => t.Id).Select(t => t.First()).ToList();
            #endregion

List对象集合取某一属性最大值的元素

           #region List对象集合取某一属性最大值的元素
            List<TestModel> maxList = new List<TestModel>();
            maxList.Add(new TestModel { Id = 9, Name = "U3", Score = 30 });
            maxList.Add(new TestModel { Id = 9, Name = "U2", Score = 20 });
            maxList.Add(new TestModel { Id = 4, Name = "U4", Score = 40 });
            maxList.Add(new TestModel { Id = 8, Name = "U1", Score = 10 });

            // 取Id值最大的元素
            TestModel maxModel = maxList.Where(t=>t.Id == maxList.Max(tt => tt.Id)).FirstOrDefault();
            #endregion

list.Select

            #region list.Select
            List<TestModel> selectList = new List<TestModel>();
            selectList.Add(new TestModel { Id = 3, Name = "U3", Score = 30 });
            selectList.Add(new TestModel { Id = 2, Name = "U2", Score = 20 });
            selectList.Add(new TestModel { Id = 4, Name = "U4", Score = 40 });
            selectList.Add(new TestModel { Id = 1, Name = "U1", Score = 10 });

            // 取每个元素的Id属性值
            List<dynamic> selectResList = selectList.Select(
                t => (dynamic)t.Id
                ).ToList();

            // 取每个元素的Id和Name属性值
            selectResList = selectList.Select(
                t => (dynamic)new { t.Id, t.Name }
                ).ToList();
            #endregion

 

posted @ 2021-01-11 11:31  温故纳新  阅读(727)  评论(0编辑  收藏  举报