C# List去重

1.List中的元素实现IEquatabe接口,并提供Equals方法和GetHashCode方法。

2.使用表达式

users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i)

去重,这条语句返回结果只保留users这个List中重复的元素的第一个(name相等认为重复)。

3.使用循环,判断每个元素是否重复

using System;
using System.Collections.Generic;
using System.Linq;

namespace NonDuplicateList
{
    class Program
    {
        static void Main(string[] args)
        {
            List<User> users = new List<User>();
            users.Add(new User("张三", "永丰路299号"));
            users.Add(new User("张三", "上地西路8号"));//重复项,去重后将删掉
            users.Add(new User("李四", "海鹰路甲一号"));

            List<User> nonDuplicateList1 = users.Distinct().ToList();//通过User类的Equals实现去重
            List<User> nonDuplicateList2 = users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i).ToList();//Lambda表达式去重
            List<User> nonDuplicateList3 = new List<User>();//通过循环方式去重
            foreach(User user in users)
            {
                if(nonDuplicateList3.Exists(x=>x.name==user.name) == false)
                {
                    nonDuplicateList3.Add(user);
                }
            }

            foreach(List<User> list in new Object[]{nonDuplicateList1,nonDuplicateList2,nonDuplicateList3})//打印出三个List的元素
            {
                Console.Write("nonDuplicateList:\r\n");
                foreach(User u in list)
                {
                    Console.WriteLine("\t" + u.ToString());
                }
            }
            Console.Read();
        }
    }

    class User:IEquatable<User>//继承IEquatable接口,实现Equals方法。List就可以使用Distinct去重
    {
        public string name { get; set; }
        string address;

        public User(string _name, string _address)
        {
            name = _name;
            address = _address;
        }

        public override string ToString()
        {
            return string.Format("name:{0},\taddress:{1}", name, address);
        }

        public bool Equals(User other)
        {
            return this.name == other.name;
        }
        public override int GetHashCode()
        {
            return name.GetHashCode();
        }
    }
}

posted on 2022-10-11 16:29  糯米白白  阅读(911)  评论(0编辑  收藏  举报

导航