Check whether all the elements in a collection are unique or not. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Check whether all the elements in a collection are unique or not.

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;//from w  w  w .  j  av a2 s  . c  o  m

public class Main{
        /// <summary>
    /// Checkst whether all the elements in a collection are unique or not.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="target">The collection.</param>
    /// <returns></returns>
    public static bool Unique<T>(this IEnumerable<T> target) where T: System.IComparable
    {
        /*
         * TODO: LINQ solution?
         *  - Ivan
         */
        for (int i = 0; i < target.Count(); i++)
        {
            for (int j = 0; j < target.Count(); j++)
            {
                if (i != j && target.ElementAt(i).CompareTo(target.ElementAt(j))==0)
                {
                    return false;
                }
            }
        }

        return true;
    }
}

Related Tutorials