C# List 去重
Posted 温故纳新
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# List 去重相关的知识,希望对你有一定的参考价值。
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 去重的主要内容,如果未能解决你的问题,请参考以下文章