C# remove duplicate values according to the specified field of the object

PersonInfo class:

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

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

PersonInfoCompareByName comparison class:

    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();
            }
        }
    }

The following code creates a new list and removes duplicates:

        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());
            }
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324931849&siteId=291194637