سؤال

There are situations in which a method should be used with yield return, but not in others.

The question is that if a method with yield return is used to assign values ​​to a variable only one item is returned.

In this situation two methods will be needed, one for regular use and the other with yield return.

Is there some way to use the method with yield return outside a loop?

هل كانت مفيدة؟

المحلول

Do you mean can you use yield return outside of a loop?

The answer is yes:

IEnumerable<string> GetStrings()
{
    yield return "foo";
    yield return "bar";
    yield return "baz";
}

...but this would be an unusual use case of yield return.

نصائح أخرى

A method that uses yield return will return an IEnumerable and possibly something more specific like an IEnumerable<int>. If you are only interested in the first item, you can call:

int myInt = myYieldReturnMethod().First();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top