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?
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. }
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.
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 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.
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
{
// ...
}
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With