简体   繁体   English

返回多个对象

[英]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. 因此,如果我需要绘制2或3个项目,则只有第一个项目。 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? 为什么不使用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. 第一个返回一个IEnumerable ,可用于迭代列表。 The second example iterates through the items once and stores them in a list. 第二个示例遍历项目一次并将它们存储在列表中。

This is also a candidate for yield . 这也是yield的候选者。 Like the first example, this returns IEnumerable<T> . 与第一个示例一样,它返回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. 第一种方法是创建一个具有2个或更多属性的类。

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. 例如,您将返回List<string>

You can use the yield keyword and return IEnumerable instead: 您可以使用yield关键字并返回IEnumerable:

Yield interacts with the foreach-loop. 产量与foreach循环相互作用。 It is a contextual keyword: yield is a keyword only in certain statements. 它是一个上下文关键字:yield只是某些语句中的关键字。 It allows each iteration in a foreach-loop be generated only when needed. 它允许仅在需要时生成foreach循环中的每次迭代。 In this way it can improve performance. 通过这种方式,它可以提高性能。

http://www.dotnetperls.com/yield http://www.dotnetperls.com/yield

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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