1

i have to chek if all elements of a List<bool> are true or all elements are false

List<bool> b1 = new List<bool>() { true, true, true, true }; //valid
List<bool> b2 = new List<bool>() { false, false, false, false }; //valid
List<bool> b3 = new List<bool>() { true, false, false, true }; //not valid

Is there a Linq approach instead of my current loop?

bool isValid = true;
for (int i = 1; i < b3.Count; i++)
{
    if (b3[i] != b3[i - 1])
        isValid = false;
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • 1
    You mean the LINQ `All()` extension method...? – CodeCaster Sep 03 '15 at 13:44
  • http://stackoverflow.com/questions/5307172/check-if-all-items-are-the-same-in-a-list, http://stackoverflow.com/questions/6681351/c-sharp-check-if-all-strings-in-list-are-the-same, http://stackoverflow.com/questions/6956096/check-if-all-list-items-have-the-same-member-value-in-c-sharp, http://stackoverflow.com/questions/4390406/using-linq-or-otherwise-how-do-check-if-all-list-items-have-the-same-value-and – CodeCaster Sep 03 '15 at 13:46
  • Would this be faster than `All`: `var isAllTrue = !b3.Any(x => !x);` – Khanh TO Sep 03 '15 at 13:48
  • Enumerable.Range(0, b3.Length - 1).All(i => b3[i] == b3[i+1) – Dennis_E Sep 03 '15 at 13:52

1 Answers1

4
bool result = myList.All(a => a) || myList.All(a => !a);

This should work

David Pilkington
  • 13,528
  • 3
  • 41
  • 73