我怎样才能返回一个空IEnumerable的? [英] How can I return an empty IEnumerable?

查看:339
本文介绍了我怎样才能返回一个空IEnumerable的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,并建议给予的在这个问题,我已经决定修改这个原始的方法,并询问是否有在IEnumarable返回任何值,如果不是返回一个IEnumerable没有值。

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 it, if not return an IEnumerable with no values.

下面是方法:

public IEnumerable<Friend> FindFriends()
        {
            //Many thanks to Rex-M for his help with this one.
            //http://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语句里面,我不知道我怎么会做这个。请问像这样的工作。

Since everything is inside the return statement, I don't know how I could do this. Would something like this work?

public IEnumerable<Friend> FindFriends()
        {
            //Many thanks to Rex-M for his help with this one.
            //http://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空:

Here is the calling code, I don't want it to receive a null IEnumerable at any time:

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

        }

感谢您的时间。

推荐答案

您可以使用列表? Enumerable.Empty<朋友>(),或 FindFriends 收益 Enumerable.Empty<朋友>()

这篇关于我怎样才能返回一个空IEnumerable的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆