Does C# have IsNullOrEmpty for List/IEnumerable?

前端 未结 10 537
一生所求
一生所求 2020-12-23 11:04

I know generally empty List is more prefer than NULL. But I am going to return NULL, for mainly two reasons

  1. I have to check and handle null values explicitly,
10条回答
  •  难免孤独
    2020-12-23 11:34

    I modified the suggestion from Matthew Vines to avoid the "Possible multiple enumeration of IEnumerable" - problem. (see also the comment from Jon Hanna)

    public static bool IsNullOrEmpty(this IEnumerable items)
        => items == null
        || (items as ICollection)?.Count == 0
        || !items.GetEnumerator().MoveNext();
    

    ... and the unit test:

    [Test]
    public void TestEnumerableEx()
    {
        List list = null;
        Assert.IsTrue(list.IsNullOrEmpty());
    
        list = new List();
        Assert.IsTrue(list.IsNullOrEmpty());
    
        list.AddRange(new []{1, 2, 3});
        Assert.IsFalse(list.IsNullOrEmpty());
    
        var enumerator = list.GetEnumerator();
        for(var i = 1; i <= list.Count; i++)
        {
            Assert.IsFalse(list.IsNullOrEmpty());
            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(i, enumerator.Current);
        }
    
        Assert.IsFalse(list.IsNullOrEmpty());
        Assert.IsFalse(enumerator.MoveNext());
    }
    

提交回复
热议问题