0

I have a class Person with two properties, genre and IsDead. I want to know if all men are death or not, in a list.

I am using this way:

if(myList.Where(x=> x.Genre == "MALE").All(x=> x.IsDeath == true));

But I don't know if there are other better option, instead of using a where and set all the properties in the All, Any... function.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

1 Answers1

2

You can also do.

if(!myList.Any(x => x.Genre == "MALE" && !x.IsDeath))
ElectricRouge
  • 1,239
  • 3
  • 22
  • 33
  • 1
    OP wants _to know if all men are death_ Your solution will return true if any man is dead – Fabio Nov 03 '16 at 12:27
  • 1
    Just add ! before myList.Any(x => x.Genre == "MALE" && !x.IsDeath) – Samvel Petrosov Nov 03 '16 at 12:30
  • 1
    @S.Petrosov - this is very "bad" and unreadable solution. Just use `All` method – Fabio Nov 03 '16 at 12:34
  • I agree with @Fabio. Using `!Any` will force it to iterate through the entire sequence whereas using `All`, it can quit iterating as soon as if finds a Male who is not dead. Also `All` is easier to read. – Chris Dunaway Nov 03 '16 at 16:20
  • @ChrisDunaway I agree that `!Any` is confusing to read. But I don't think `Any` will force it to iterate through the entire sequence. Do you have any reference to this? Because according to this(https://stackoverflow.com/questions/9027530/linq-not-any-vs-all-dont) both are same. – ElectricRouge Nov 03 '16 at 16:52
  • `All` is implemented with a not operator before the predicate, but I think you're right. They both might short circuit under certain conditions now that I look at it closer. – Chris Dunaway Nov 03 '16 at 17:55