Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a property that is IEnumerable<T>?

I have a class that's IEnumerable<T> where I want to have different properties that provides a filtered IEnumerable<T> access.

So for instance:

class Shape
   ShapeType = Box/Sphere/Pyramid

class ShapeCollection : IEnumerable<Shape>
{
   public IEnumerable<Shape> OnlyBox
   {
       foreach(var s in this)
       {
           if (s.ShapeType == Box)
               yield return s;
       }
   }
}

Is this how it should be? Just not sure, about it completely.

Thanks.

like image 570
Joan Venge Avatar asked Sep 02 '10 18:09

Joan Venge


2 Answers

Sure, but you might want to rewrite it as

public IEnumerable<Shape> OnlyBox
{
    get { return this.Where(x => x.ShapeType == ShapeType.Box); }
}

which does the exact same thing.

like image 178
mqp Avatar answered Sep 29 '22 13:09

mqp


class ShapeCollection : IEnumerable<Shape>
{
   public IEnumerable<Shape> OnlyBoxes
   {
       get { return this.Where(s => s.ShapeType == Box); }
   }
}

You were missing the get/parenthesis to make it a method. Also what is Box, did you mean ShapeType.Box? Also maybe rename it to OnlyBoxes, seems more descriptive.

like image 38
Yuriy Faktorovich Avatar answered Sep 29 '22 14:09

Yuriy Faktorovich