black eyed pea
black eyed pea

Reputation: 427

Linq : How do I test a List<bool> for condition where any one of its values == true?

I have a list,

List<bool> MyList;
MyList.Add(true);
MyList.Add(false);
MyList.Add(false);

What is a clean way to use linq to test if any value is true? I tried

MyList.Find(SomeBoolean=>SomeBoolean)

but the result is weird.

Upvotes: 5

Views: 3334

Answers (4)

catalyst
catalyst

Reputation: 1

myList is a list of bool

myList= getSelectedChannels(); List allTrue= myList.FindAll(a => a == true);

allTrue will be a list of bool that match the criteria (bool is true). Now just say allTrue.Count to get the number of items in that list.

Upvotes: 0

spajce
spajce

Reputation: 7082

If you want to List all the true value

List<bool> MyList = new List<bool>();
MyList.Add(true);
MyList.Add(false);
MyList.Add(false);
var listTrue = MyList.Where(c => c);

I wonder, what is your actual Class because if you want to .Find is the same result.

var b = MyList.Find(c => c)

maybe you forgot to declare the var or DataType?

Upvotes: 1

devdigital
devdigital

Reputation: 34349

Use Any

var anyTrue = MyList.Any(i => i);

Upvotes: 4

xlecoustillier
xlecoustillier

Reputation: 16351

Try :

bool test = MyList.Any(x => x);

But you have to initialize your list before inserting anything.

Upvotes: 10

Related Questions