Distinct not working with LINQ to Objects

后端 未结 9 1813
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:20
class Program
{
    static void Main(string[] args)
    {
        List books = new List 
        {
            new Book
            {
                


        
9条回答
  •  臣服心动
    2020-11-22 12:57

    You can use extension method on list which checks uniqueness based on computed Hash. You can also change extension method to support IEnumerable.

    Example:

    public class Employee{
    public string Name{get;set;}
    public int Age{get;set;}
    }
    
    List employees = new List();
    employees.Add(new Employee{Name="XYZ", Age=30});
    employees.Add(new Employee{Name="XYZ", Age=30});
    
    employees = employees.Unique(); //Gives list which contains unique objects. 
    

    Extension Method:

        public static class LinqExtension
            {
                public static List Unique(this List input)
                {
                    HashSet uniqueHashes = new HashSet();
                    List uniqueItems = new List();
    
                    input.ForEach(x =>
                    {
                        string hashCode = ComputeHash(x);
    
                        if (uniqueHashes.Contains(hashCode))
                        {
                            return;
                        }
    
                        uniqueHashes.Add(hashCode);
                        uniqueItems.Add(x);
                    });
    
                    return uniqueItems;
                }
    
                private static string ComputeHash(T entity)
                {
                    System.Security.Cryptography.SHA1CryptoServiceProvider sh = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    string input = JsonConvert.SerializeObject(entity);
    
                    byte[] originalBytes = ASCIIEncoding.Default.GetBytes(input);
                    byte[] encodedBytes = sh.ComputeHash(originalBytes);
    
                    return BitConverter.ToString(encodedBytes).Replace("-", "");
                }
    

提交回复
热议问题