Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return more than one object

Tags:

c#

I have a method that checks through a list of items and returns the item if the conditions in the method are met. The problem is that sometimes I have more than one item that needs to be returned to be drawn on the screen. So if I have 2 or 3 items that need to be drawn, only the first one is. This may be a problem with my draw code but I'm not sure yet.

foreach(Item i in List)
{
    if conditions are met
    {
        return i

Is there a way to check for more than one item being returned in this method?

like image 271
Christian Frantz Avatar asked Apr 19 '26 11:04

Christian Frantz


1 Answers

Why not use LINQ?

// return an enumerable
return items.Where( item => item.SomeCondition );

Or

// execute once and store in a list
return items.Where( item => item.SomeCondition ).ToList();

There's an important difference between these two examples. The first returns an IEnumerable that can be used to iterate over the list. The second example iterates through the items once and stores them in a list.

This is also a candidate for yield. Like the first example, this returns IEnumerable<T>.

foreach( var item in items )
{
    if( conditions ){
         yield return item;
    }
}
  • More info on deferred execution.
  • Where() reference
  • yield reference
like image 158
Tim M. Avatar answered Apr 22 '26 01:04

Tim M.