C#根据对象的指定字段去除重复值

PersonInfo类:

    public class PersonInfo
    {
        public int Index;
        public string Name;

        public override string ToString()
        {
            return string.Format("Index:{0}, Name:{1}", Index, Name);
        }
    }

PersonInfoCompareByName比较类:

    public class PersonInfoCompareByName : IEqualityComparer<PersonInfo>
    {
        public bool Equals(PersonInfo x, PersonInfo y)
        {
            if (x != null && y != null && x.Name == y.Name)
                return true;

            return false;
        }

        public int GetHashCode(PersonInfo obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return obj.Name.GetHashCode();
            }
        }
    }

下面的代码是新建一个列表,然后去除重复项:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<PersonInfo> PersonList = new List<PersonInfo>();
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    var info = new PersonInfo();
                    info.Index = j;
                    info.Name = "Name" + i;
                    PersonList.Add(info);
                }
            }

            var items = PersonList.Distinct(new PersonInfoCompareByName());
            foreach (var item in items)
            {
                Console.WriteLine(item.ToString());
            }
        }

猜你喜欢

转载自www.cnblogs.com/wzwyc/p/8946359.html