How to check if IEnumerable is null or empty?

前端 未结 22 1089
梦如初夏
梦如初夏 2020-11-27 12:33

I love string.IsNullOrEmpty method. I\'d love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection he

22条回答
  •  臣服心动
    2020-11-27 13:05

    Since some resources are exhausted after one read, I thought why not combine the checks and the reads, instead of the traditional separate check, then read.

    First we have one for the simpler check-for-null inline extension:

    public static System.Collections.Generic.IEnumerable ThrowOnNull(this System.Collections.Generic.IEnumerable source, string paramName = null) => source ?? throw new System.ArgumentNullException(paramName ?? nameof(source));
    
    var first = source.ThrowOnNull().First();
    

    Then we have the little more involved (well, at least the way I wrote it) check-for-null-and-empty inline extension:

    public static System.Collections.Generic.IEnumerable ThrowOnNullOrEmpty(this System.Collections.Generic.IEnumerable source, string paramName = null)
    {
      using (var e = source.ThrowOnNull(paramName).GetEnumerator())
      {
        if (!e.MoveNext())
        {
          throw new System.ArgumentException(@"The sequence is empty.", paramName ?? nameof(source));
        }
    
        do
        {
          yield return e.Current;
        }
        while (e.MoveNext());
      }
    }
    
    var first = source.ThrowOnNullOrEmpty().First();
    

    You can of course still call both without continuing the call chain. Also, I included the paramName, so that the caller may include an alternate name for the error if it's not "source" being checked, e.g. "nameof(target)".

提交回复
热议问题