¿Cómo puedo devolver un vacío IEnumerable?


Dado el siguiente código y las sugerencias dadas en esta pregunta, he decidido modificar este método original y preguntar si hay algún valor en el returnumarable devolverlo, si no devolver unEnumerable sin valores.

Aquí está el método:

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

Dado que todo está dentro de la declaración return, no se como podría hacer esto. ¿Funcionaría algo como esto?

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

El método anterior no funciona, y de hecho no se supone que; simplemente siento ilustra mis intenciones. Creo que debo especificar que el código no funciona porque no se puede crear una instancia de una clase abstracta.

Aquí está el código de llamada, no quiero recibir un null IEnumerable en cualquier momento:

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

        }

Gracias por su tiempo.

Author: Community, 2010-07-12

5 answers

Puedes usar list ?? Enumerable.Empty<Friend>(), o hacer que FindFriends devuelva Enumerable.Empty<Friend>()

 453
Author: Michael Mrozek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-12 15:24:46

Usted podría volver Enumerable.Empty<T>().

 129
Author: LukeH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-16 18:43:19

En cuanto a mí, la manera más elegante es yield break

 82
Author: Pavel Tupitsyn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 04:39:07

Eso es, por supuesto, solo una cuestión de preferencia personal, pero escribiría esta función usando 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
                }
        }
    }
}
 8
Author: Chaos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-12 15:40:03

Creo que la forma más sencilla sería

 return new Friend[0];

Los requisitos del retorno son simplemente que el método devuelva un objeto que implemente IEnumerable<Friend>. El hecho de que en diferentes circunstancias devuelva dos tipos diferentes de objetos es irrelevante, siempre y cuando ambos implementenumumerable.

 1
Author: James Curran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-12 15:38:00