简体   繁体   中英

Return more than one object

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?

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;
    }
}

You can do something like this by returning a list of items meeting the condition:

List<YourItemType> itemsMeetingCondition = new List<YourItemType>();
foreach(Item i in List)
{
    if( conditions are met)
    {
        itemsMeetingCondition.Add(i);
    }
}
return itemsMeetingCondition;

First way is to make a class with 2 or more properties.

Here would be a return class:

public class ColorSelection
    {
        public string ColorCode { get; set; }
        public bool IsBold { get; set; }

    }

In your code you would return this at some point.

The second way is used if they are all the same type. You would return a List<string> for example.

You can use the yield keyword and return IEnumerable instead:

Yield interacts with the foreach-loop. It is a contextual keyword: yield is a keyword only in certain statements. It allows each iteration in a foreach-loop be generated only when needed. In this way it can improve performance.

http://www.dotnetperls.com/yield

public IEnumerable<Item> GetItems()
{
    foreach(Item i in List)
    {
        if conditions are met
        {
            yield return i;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM