Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all values in an array are equal [duplicate]

Tags:

c#

linq

The following checks if all values in a string array are equal ignoring the case

string [] StringArray = new string[]{"xxx","xXx","Xxx"}; 
bool ValuesAreEqual = false;
for(int i= 0;i<StringArray.Length;i++)
{
    if(i>=1)
    {
        ValuesAreEqual = StringArray[0].Equals(StringArray[i],StringComparison.InvariantCultureIgnoreCase);
        if(!ValuesAreEqual)
        {
            break;
        }
    }
}

How could I write this using LINQ?

like image 901
FPGA Avatar asked Apr 28 '14 11:04

FPGA


People also ask

How do I check if an array contains duplicates?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

How do you check if all values in an array are equal?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

How do you check if an array of objects has duplicate values in javaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if all elements in an array are equal in C?

How do you check if all values in an array are equal in C? Compare the lengths of arr1 and arr2 . Sort arr1 and arr2 either in ascending or descending order. For each index i of the array, compare arr1[i] and arr2[i] to be equal.


2 Answers

If you want to know if all are equal Enumerable.All is efficient and readable:

string firstItem = StringArray[0];
bool allEqual = StringArray.Skip(1)
  .All(s => string.Equals(firstItem, s, StringComparison.InvariantCultureIgnoreCase));

All breaks also on the first comparison that returns false. Note that i've used the static string.Equals to prevent null-reference exceptions on null objects.

By the way, your loop is incorrect since you start to compare at index 2 instead of 1 here:

if(i > 1 ) // indices are zero based
{
    // ...
}
like image 200
Tim Schmelter Avatar answered Sep 20 '22 12:09

Tim Schmelter


string[] StringArray = new string[] {"xxx,xXx,Xxx"};
bool areEqual = StringArray.Select(s => s.ToLower()).Distinct().Count()==1;

bool areEqual = StringArray.GroupBy(s => s.ToLower()).Count() == 1;

just to be original here:)

like image 25
Andrew Avatar answered Sep 21 '22 12:09

Andrew