C# List集合基礎操做

這裏介紹一下C# list的基礎操做: 去重、差集、並集、交集ide

 

下面,咱們看看例子。咱們建立了一個User實體,包含兩個list,User實體若是Id相等,則相等。this

users1是id 1到4的集合,users2是id 4到8的集合。spa

            List<User> users1 = new List<User>();
            users1.Add(new User() {Id = 1, Age = 1, Name = "Name01"});
            users1.Add(new User() { Id = 2, Age = 2, Name = "Name02" });
            users1.Add(new User() { Id = 3, Age = 3, Name = "Name03" });
            users1.Add(new User() { Id = 4, Age = 4, Name = "Name04" });

            List<User> users2 = new List<User>();
            users2.Add(new User() { Id = 4, Age = 44, Name = "Name044" });
            users2.Add(new User() { Id = 5, Age = 55, Name = "Name01" });
            users2.Add(new User() { Id = 6, Age = 66, Name = "Name06" });
            users2.Add(new User() { Id = 7, Age = 77, Name = "Name07" });
            users2.Add(new User() { Id = 8, Age = 88, Name = "Name08" });

            //把兩個list合併在一塊兒
            var result1 = new List<User>();
            result1.AddRange(users1);
            result1.AddRange(users2);

            //去重:在result1中去重
            var result2 = result1.Distinct().ToList();

            //差集:users1在users2之中的差集
            var result3 = users1.Except(users2).ToList();

            //並集:users1與users2 合起來不重複的元素
            var result4 = users1.Union(users2).ToList();

            //交集:users1與users2 相同的元素
            var result5 = users1.Intersect(users2).ToList();

 

下面咱們看看User實體的定義:code

須要注意的是,咱們重寫了User的GetHashCode與Equals方法來比較對象是否相等。orm

    public class User
    {
        public long Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            User u = (User) obj;
            if (this.Id != 0 && u.Id == this.Id)
                return true;
            return false;
            
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }

        public override string ToString()
        {
            return string.Format("id=" + this.Id);
        }
    }


能夠關注本人的公衆號,多年經驗的原創文章共享給你們。對象

 
 

相關文章
相關標籤/搜索