How can I return an empty IEnumerable?

前端 未结 6 710
说谎
说谎 2020-12-12 12:14

Given the following code and the suggestions given in this question, I\'ve decided to modify this original method and ask if there are any values in the IEnumarable return i

相关标签:
6条回答
  • 2020-12-12 12:39

    I think the simplest way would be

     return new Friend[0];
    

    The requirements of the return are merely that the method return an object which implements IEnumerable<Friend>. The fact that under different circumstances you return two different kinds of objects is irrelevant, as long as both implement IEnumerable.

    0 讨论(0)
  • 2020-12-12 12:48
    public IEnumerable<Friend> FindFriends()
    {
        return userExists ? doc.Descendants("user").Select(user => new Friend
            {
                ID = user.Element("id").Value,
                Name = user.Element("name").Value,
                URL = user.Element("url").Value,
                Photo = user.Element("photo").Value
            }): new List<Friend>();
    }
    
    0 讨论(0)
  • 2020-12-12 12:51

    You could return Enumerable.Empty<T>().

    0 讨论(0)
  • 2020-12-12 12:54

    As for me, most elegant way is yield break

    0 讨论(0)
  • 2020-12-12 13:00

    That's of course only a matter of personal preference, but I'd write this function using yield return:

    public IEnumerable<Friend> FindFriends()
    {
        //Many thanks to Rex-M for his help with this one.
        //http://stackoverflow.com/users/67/rex-m
        if (userExists)
        {
            foreach(var user in doc.Descendants("user"))
            {
                yield return new Friend
                    {
                        ID = user.Element("id").Value,
                        Name = user.Element("name").Value,
                        URL = user.Element("url").Value,
                        Photo = user.Element("photo").Value
                    }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 13:04

    You can use list ?? Enumerable.Empty<Friend>(), or have FindFriends return Enumerable.Empty<Friend>()

    0 讨论(0)
提交回复
热议问题