Compute Hash for generic Array - CSharp System

CSharp examples for System:Array Calculation

Description

Compute Hash for generic Array

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;/* w ww .  j a  va2  s .  c om*/

public class Main{
        public static int ComputeHash<T>(this T[] data, IEqualityComparer<T> comparer = null)
        {
            unchecked
            {
                if (data == null)
                    return 0;

                if (comparer == null)
                    comparer = EqualityComparer<T>.Default;

                int hash = 17 + data.Length;
                int result = hash;
                foreach (T unknown in data)
                    result = result * 31 + comparer.GetHashCode(unknown);
                return result;
            }
        }
        public static int ComputeHash<T>(this ICollection<T> data, IEqualityComparer<T> comparer = null)
        {
            unchecked
            {
                if (data == null)
                    return 0;

                if (comparer == null)
                    comparer = EqualityComparer<T>.Default;

                int hash = 17 + data.Count;
                int result = hash;
                foreach (T unknown in data)
                    result = result*31 + comparer.GetHashCode(unknown);
                return result;
            }
        }
}

Related Tutorials