snippetcsharpCritical
How can I return an empty IEnumerable?
Viewed 0 times
emptyhowreturnienumerablecan
Problem
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
Here is the method:
Since everything is inside the return statement, I don't know how I could do this. Would something like this work?
The above method doesn't work, and in fact it's not supposed to; I just feel it illustrates my intentions. I feel I should specify that the code doesn't work because you can't create an instance of an abstract class.
Here is the calling code, I don't want it to receive a null
```
private void SetUserFriends(IEnumerable 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(contr
IEnumarable return it, if not return an IEnumerable with no values.Here is the method:
public IEnumerable 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
});
}Since everything is inside the return statement, I don't know how I could do this. Would something like this work?
public IEnumerable 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();
}
}The above method doesn't work, and in fact it's not supposed to; I just feel it illustrates my intentions. I feel I should specify that the code doesn't work because you can't create an instance of an abstract class.
Here is the calling code, I don't want it to receive a null
IEnumerable at any time:```
private void SetUserFriends(IEnumerable 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(contr
Solution
You can use
This can be found under the
list ?? Enumerable.Empty(), or have FindFriends return Enumerable.Empty()This can be found under the
System.Linq namespace.Context
Stack Overflow Q#3229698, score: 689
Revisions (0)
No revisions yet.