C# List<T> 集合查找、删除内容相同的引用类型元素

List 集合查找、删除内容相同的引用类型元素

  • 通常情况
  • 重写IEquatable接口

C# List<T> 集合查找、删除内容相同的引用类型元素_第1张图片

通常情况

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    internal class People
    {
        public string name;
        public People(string name) {
            this.name = name;
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        List<People> list = new List<People>();

        var t1 = new People("张三");
        var t2 = new People("张三");

        list.Add(t1);

        bool isContain = list.Contains(t2);
        bool isRemoved = list.Remove(t2);
        
        Debug.Log(isContain); // false
        Debug.Log(isRemoved); // false
    }

}


如上所示,因为People类没有实现IEquatable接口,调用集合Contains、Remove方法时使用Object类的Equals() 方法比较这些元素,默认实现代码对值类型按位比较,对引用类型只比较其引用(内存地址),t1和t2是两个不同引用对象,所以无法用t2查询或删除集合中的t1。

重写IEquatable接口

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    internal class People:IEquatable<People>
    {
        public string name;
        public People(string name) {
            this.name = name;
        }

        public bool Equals(People other)
        {
            return name.Equals(other.name);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        List<People> list = new List<People>();

        var t1 = new People("张三");
        var t2 = new People("张三");

        list.Add(t1);

        bool isContain = list.Contains(t2);
        bool isRemoved = list.Remove(t2);

        Debug.Log(isContain); // true
        Debug.Log(isRemoved); // true
    }

}

如上所示,在People类实现了IEquatable接口并重写Equals方法, t1和t2具有相同name,因此可以用t2成功查询并删除掉集合中的t1。

你可能感兴趣的:(C#,c#,List,集合)