c# - 如何返回一个空的 IEnumerable?

标签 c# ienumerable

给出以下代码和给出的建议in this question ,我决定修改这个原始方法并询问 IEnumarable 中是否有任何值返回它,如果没有返回一个没有值的 IEnumerable

方法如下:

public IEnumerable<Friend> FindFriends()
{
    //Many thanks to Rex-M for his help with this one.
    //https://stackoverflow.com/users/67/rex-m

    return 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
    });
}

由于所有内容都在 return 语句中,我不知道该怎么做。这样的东西行得通吗?

public IEnumerable<Friend> FindFriends()
{
    //Many thanks to Rex-M for his help with this one.
    //https://stackoverflow.com/users/67/rex-m
    if (userExists)
    {
        return 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
        });
    }
    else
    { 
        return new IEnumerable<Friend>();
    }
}

上述方法行不通,实际上也不应该;我只是觉得它说明了我的意图。 我觉得我应该指定代码不起作用,因为您不能创建抽象类的实例。

这里是调用代码,我不希望它在任何时候都收到一个空的IEnumerable:

private void SetUserFriends(IEnumerable<Friend> list)
{
    int x = 40;
    int y = 3;

    foreach (Friend friend in list)
    {
        FriendControl control = new FriendControl();
        control.ID = friend.ID;
        control.URL = friend.URL;
        control.SetID(friend.ID);
        control.SetName(friend.Name);
        control.SetImage(friend.Photo);

        control.Location = new Point(x, y);
        panel2.Controls.Add(control);

        y = y + control.Height + 4;
    } 
}

感谢您的宝贵时间。

最佳答案

您可以使用 list ?? Enumerable.Empty<Friend>() , 或者有 FindFriends返回 Enumerable.Empty<Friend>()

这可以在 System.Linq 下找到命名空间。

关于c# - 如何返回一个空的 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3229698/

相关文章:

c# - 如何使用 MongoDB 访问深层嵌套数组(ASP.NET Core 2.2)

c# - IComparer 可以用于在填充列表时对列表进行哈希吗?

c# - VSCode intellisense 不适用于一个 c# 项目的解决方案

c# - 查找在当前区域性中所有字母之后排序的字符串的最佳方法

c# - 数据对象属性的最佳实践 : IEnumerable vs Array

c# - 来自 yielding 的 ienumerable 是否可以为空?

c# - 有没有办法在不使用 GDI+/WinForms "Graphics"类的情况下检索设备的 DPI?

c# - 保护 foreach 循环免受 null 影响的更智能方法

c# - IEnumreable 动态和 lambda

c# - PropertyInfo.GetValue(object) 因 IEnumerable<T> [C#, Reflection] 而失败