Reputation: 28741
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.
Upvotes: 2
Views: 401
Reputation: 14376
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.
Upvotes: 3
Reputation: 30688
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]);
Upvotes: 4
Reputation: 1499760
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;
}
}
}
Upvotes: 8