C#集合用Distinct去掉重复的元素,IEqualityComparer原理

 json测试数据:

[
	{
		"Type": "ROLETYPE_USER",
		"Value": "9846cdac-ae21-4be4-a284-50158dd19606"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "4f6665fc-b0b9-4865-bf12-eff06810efa3"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "ca4dbf59-d248-4538-9fe8-62e1cafcde6c"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "7c4852c2-b2c2-4688-92a3-3dd1b00bacf8"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "982a2f9d-a079-4613-825f-c2ef9801eb3e"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "ca4dbf59-d248-4538-9fe8-62e1cafcde6c"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "ca4dbf59-d248-4538-9fe8-62e1cafcde6c"
	},
	{
		"Type": "ROLETYPE_ROLE",
		"Value": "76f62bf8-bf24-48c1-b70e-7628ff08c3fb"
	},
	{
		"Type": "ROLETYPE_USER",
		"Value": "982a2f9d-a079-4613-825f-c2ef9801eb3e"
	}
]

 实体类型

    public class TempSetting
    {
       public string Type { get; set; }
        public Guid Value { get; set; }
    }

创建比较类,继承自IEqualityComparer,一般要选择特征值字段来设置hashCode值返回才有效果,或者直接设置哈希值返回1(这样每次都会调用Equals方法,但这样性能低)。IEqualityComparer比较对象是否相等是优先调用GetHashCode()比较哈希值是否相等,不相等的就不会调用Equals方法,如果哈希值相等的才会调用调用Equals方法再比较是否相等最终确认,所以 GetHashCode方法里面要设置特征值字段来返回hashcode,这样速度才快,性能高

 public class CompareSetting : IEqualityComparer
    {
        public bool Equals(TempSetting x, TempSetting y)
        {
            return x.Value == y.Value;
        }

        public int GetHashCode(TempSetting obj)
        {
            if (obj == null)
            {
                return 0;
            }
            //return obj.GetHashCode();//比较不出来重复的
            //string km = obj.Type + obj.Value;//比较重复值成功
            //return km.GetHashCode();
            //GetHashCode推荐选择自己看中的特征值字段来进行比较,否则有时候可能比较不成功
            return obj.Value.GetHashCode();
        }
    }

//测试比较
        string funs = "[{\"Type\":\"ROLETYPE_USER\",\"Value\":\"9846cdac-ae21-4be4-a284-50158dd19606\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"4f6665fc-b0b9-4865-bf12-eff06810efa3\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"ca4dbf59-d248-4538-9fe8-62e1cafcde6c\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"7c4852c2-b2c2-4688-92a3-3dd1b00bacf8\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"982a2f9d-a079-4613-825f-c2ef9801eb3e\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"ca4dbf59-d248-4538-9fe8-62e1cafcde6c\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"ca4dbf59-d248-4538-9fe8-62e1cafcde6c\"},{\"Type\":\"ROLETYPE_ROLE\",\"Value\":\"76f62bf8-bf24-48c1-b70e-7628ff08c3fb\"},{\"Type\":\"ROLETYPE_USER\",\"Value\":\"982a2f9d-a079-4613-825f-c2ef9801eb3e\"}]";
            List list = Newtonsoft.Json.JsonConvert.DeserializeObject>(funs);
            var list2 = list.Distinct(new CompareSetting());

 

 

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