Yield Return with Null

前端 未结 6 1752
长发绾君心
长发绾君心 2020-12-16 09:52

Is there any way to optionally return a null with a \"return yield\" driven iterator?

I would like to return a null in some cases and I don\'t think this is particul

6条回答
  •  自闭症患者
    2020-12-16 10:31

    You're not using an enumerable as it was intended (to iterate objects in a collection). If you want to keep your code similar to what it is now, you should do something like this:

    static void Main(string[] args)
    {
        var Items = GetItems();
    
        foreach (var item in Items) //this will not enter the loop because there are no items in the Items collection
        {
                Console.WriteLine(item);
        }
    
        //if you still need to know if there were items, check the Count() extension method
        if(Items.Count() == 0)
        {
          Console.WriteLine("0 items returned");
        }
    
    
    }
    
    static IEnumerable GetItems()
    {
        if (false)
        {
            yield return "Andy";
            yield return "Jennifer";
        }
    
        yield break;
    }
    

提交回复
热议问题