首页 > Windows开发 > 详细

C# List 去重

时间:2021-05-15 19:18:49      阅读:33      评论:0      收藏:0      [点我收藏+]
using DailyCoding.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DailyCoding.Code
{
    [ClassInfo("List遍历删除重复元素")]
    public class _20210515_1
    {
        public void Run()
        {
            var list = new List<_20210515_1_Model>();
            list.Add(new _20210515_1_Model { Id = 1, Name = "N1", Addr = "A1" });
            list.Add(new _20210515_1_Model { Id = 1, Name = "N1", Addr = "A1" });
            list.Add(new _20210515_1_Model { Id = 2, Name = "N2", Addr = "A2" });
            list.Add(new _20210515_1_Model { Id = 2, Name = "N2", Addr = "A2" });
            list.Add(new _20210515_1_Model { Id = 3, Name = "N3", Addr = "A3" });
            list.Add(new _20210515_1_Model { Id = 3, Name = "N3", Addr = "A3" });

            // 根据id值去重
            var idDistinctList = list.GroupBy(t => t.Id).Select(t => t.First());

            // 从后往前遍历,删除 Name和Addr 重复的元素
            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list.Where(t => t.Name == list[i].Name && t.Addr == list[i].Addr).Count() > 1)
                    list.RemoveAt(i);
            }
        }
    }

    public class _20210515_1_Model
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Addr { get; set; }
    }
}

 

C# List 去重

原文:https://www.cnblogs.com/tomorrow0/p/14771906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!