List集合id去重

实现model数组 (model 字段为 id name type)按id去重,Distinct实现
Model m1 = new Model(1, "张三", "男");
Model m2 = new Model(2, "李四", "男");
Model m3 = new Model(1, "王五", "男");
List<Model> list = new List<Model>();
list.Add(m1);
list.Add(m2);
list.Add(m3);

回答

去重后留“张三”还是“王五”?

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

namespace DistinctDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var people = new List<Person>() { 
                new Person{ Id = 1, Name = "张三"},
                new Person{ Id = 2, Name = "赵四"},
                new Person{ Id = 1, Name = "王五"},
            };

            Distinct<Person>(ref people, MyCondition);
        }

        private static bool MyCondition(Person person1, Person person2)
        {
            if (person1 == null && person2 == null)
            {
                return true;
            }
            if (person1 == null || person2 == null)
            {
                return false;
            }

            return person1.Id == person2.Id;
        }

        static void Distinct<T>(ref List<T> list, Func<T, T, bool> Condition) // ref不用也行,加上语义明确一些
        {
            if (list != null && list.Count > 1)
            {
                for (int i = 1; i < list.Count; i++)
                {
                    for (int j = 0; j < i; j++)
                    {
                        if (Condition(list[i], list[j]))
                        {
                            list.RemoveAt(i--);
                        }
                    }
                }
            }
        }
    }

    internal class Person
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

或者:

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

namespace DistinctDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var people = new List<Person>() { 
                new Person{ Id = 1, Name = "张三"},
                new Person{ Id = 2, Name = "赵四"},
                new Person{ Id = 1, Name = "王五"},
            };

            people = people.Distinct(new MyEqualityComparer()).ToList();
        }
    }

    internal class Person
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    internal class MyEqualityComparer : IEqualityComparer<Person>
    {
        public bool Equals(Person x, Person y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Person obj)
        {
            return obj.Id.GetHashCode();
        }
    }
}

以上是List集合id去重的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>