其他, 原创

ASP.NET 数组去除重复信息 IEqualityComparer实例

假设 定义List<ChatUserName> list = 这里是源数据的信息;
定义List<ChatUserName> listUser为去除重复后的用户信息;
核心代码就是

List<ChatUserName> list = this.JsonDeserialize<List<ChatUserName>>(usersJson);//这里是得到list的用户数据
IEnumerable noduplicates = list.Distinct(new UserComparer());
List listUser = new List<ChatUserName>();
foreach (var userName in noduplicates)
{
    listUser.Add(new ChatUserName() { name = userName.name, nickname = userName.nickname  });
}
userRegroup = JsonSerializer<List<ChatUserName>>(listUser);//这里是将List数据转换为json字符串

这里面使用到的UserComparer 以及ChatUserName 定义如下

ChatUserName:

    public class ChatUserName
    {
        public string name { get; set; }
        public string nickname { get; set; }
    }

UserComparer(这里才是重点,现在我只需要比较里面的name):

public class UserComparer : IEqualityComparer<ChatUserName>{
    public bool Equals(ChatUserName x, ChatUserName y){
        if (x.name == y.name){
            return true;
        }else{
            return false;
        }
    }
    public int GetHashCode(ChatUserName user){
        return 0;
    }
}

下面定义JsonDeserialize 函数和 JsonSerializer函数用于将json字符串转换为数组,和将数组转换为字符串, 有可能你根本就用户到下面的信息,除非你的信息也是存在字符串中。

public string JsonSerializer<T>(T t)
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream();
    ser.WriteObject(ms, t);
    string jsonString = Encoding.UTF8.GetString(ms.ToArray());
    ms.Close();
    return jsonString;
}
public T JsonDeserialize<T>(string jsonString)
{
    if (!string.IsNullOrEmpty(jsonString))
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        ms.Close();
        return obj;
    }
    else
    {
        return default(T);
    }
}

需要引用的命名空间:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.String;

(805)

Related Post