How to validate yield return default in IEnumerable?

时间秒杀一切 提交于 2021-01-28 23:11:30

问题


I am trying to check whether IEnumerable<> is null or empty but somehow my if check always fails whenever it is empty.

    private bool Update()
    {
        IEnumerable<RecordHolder> recordHolders = GetData();
        // below  check doesn't work
        if (recordHolders == null || !recordHolders.Any())
            return false;

        // .. some other code
    }

    public IEnumerable<RecordHolder> GetData()
    {
        var isSuccess = PullRemote(url);
        if (!isSuccess.Result) { yield return default; }

        // .. some other code
    }

Whenever my GetData() method returns yield return default then the subsequent if check in Update method doesn't work. Anything wrong I am doing?

I thought my if check in Update method will be able to catch yield return default but I am wrong looks like.


回答1:


I think you are looking for yield break instead of yield return default. Alternatively, you can do the first part of the operation in a regular method (not an iterator block), and special-case the return for failure cases (Array.Empty<T>() is a common choice), deferring to an iterator block (or a Select projection) for the success cases.




回答2:


When you do yield return default you are returning the default value of RecordHolder which is null.

So your IEnumerable will contain 1 item which is null.

Try returning Enumerable.Empty() or Array.Empty(); instead of your yield return default.

Example

using System;
using System.Collections.Generic;
using System.Linq;
                
public class Program
{
    public static void Main()
{
    var result = GetData();
    Console.WriteLine(result.Count()); // Prints 1
}

public static IEnumerable<MyClass> GetData()
{
    yield return default;
}

public class MyClass
{
        public string MyProperty {get;set;}
    }
}

Example here: https://dotnetfiddle.net/vVefPx



来源:https://stackoverflow.com/questions/63312797/how-to-validate-yield-return-default-in-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!