2

This is the Linq way to check whether all items are same in list.

if (list.Distinct().Skip(1).Any())

But doesn't work for a application developed earlier than .NET 3.5 What is the best optimal way to do it in non Linq way.

Tilak
  • 30,108
  • 19
  • 83
  • 131
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133

3 Answers3

8

Well you could just do:

public bool AllEqual<T>(IEnumerable<T> items)
{
    // This could be a parameter if you want
    var comparer = EqualityComparer<T>.Default;
    using (var iterator = items.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            return true; // Empty sequence
        }
        var first = iterator.Current;
        while (iterator.MoveNext())
        {
            if (!comparer.Equals(first, iterator.Current))
            {
                return false;
            }
        }
    }
    return true;
}

This works for all sequence types, not just lists. For lists it's actually slightly simpler:

public bool AllEqual<T>(IList<T> items)
{
    // This could be a parameter if you want
    var comparer = EqualityComparer<T>.Default;
    for (int i = 1; i < items.Count; i++)
    {
        if (!comparer.Equals(items[0], items[i]))
        {
            return false;
        }
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

Using Simple For loop.

var allSame = true;
for(int i=1 ; i < list.Count ; i++)
{
   if ( list[0] != list[i] )
   { 
     allSame = false;
     break;
   }
}

If you want to use Linq in .NET 2.0, you can use LinqBridge.

But your LINQ query itself is not optimal. Best is For Loop. Better LINQ query is

list.Skip(1).Any( item => item != list[0]); 
Tilak
  • 30,108
  • 19
  • 83
  • 131
3

Something a bit shorter:

public static bool AllSame<T>(List<T> list)
{
    return list.Count == 0 || list.FindAll(delegate(T x)
        { return !EqualityComparer<T>.Default.Equals(x, list[0]); }).Count == 0;
}

Tested on VS2012 with a new Framework 2.0 project.

akton
  • 14,148
  • 3
  • 43
  • 47