空の IEnumerable を返すにはどうすればよいですか? 質問する

空の IEnumerable を返すにはどうすればよいですか? 質問する

以下のコードと提案を前提としてこの質問では、私はこの元のメソッドを変更して、値があるかどうかを尋ねて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呼び出しコードは次のとおりです。いつでもnull を受け取らないようにします。

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

お時間をいただきありがとうございます。

ベストアンサー1

を使用するlist ?? Enumerable.Empty<Friend>()か、またはFindFriends戻り値を持つことができますEnumerable.Empty<Friend>()

これは名前空間の下にありますSystem.Linq

おすすめ記事