问题
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