Counting for how many instances a bool property is true – C#

  • A+

I have an IEnumerable of a certain object which has a bool property. I would like to count for how many objects this property is set to true in a compact (in terms of code lines) and readable way.

To demonstrate it, Iv'e create a class 'Obj' with a boolean property 'InnerProperty'. The static function 'CountInner' implements the defined logic above. How can I implement it in a more compactly?

public class Obj {     private bool InnerProperty { get; set; } = false;      public static int CountInner(IEnumerable<Obj> list)     {         var count = 0;         foreach (var l in list)         {             if (l.InnerProperty)             {                 count++;             }         }         return count;     } } 


You could use LINQ's Count which accepts a predicate ("a function to test each element for a condition."):

public static int CountInner(IEnumerable<Obj> list) {     return list.Count(x => x.InnerProperty); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: