【发布时间】:2010-07-07 03:46:28
【问题描述】:
特别感谢 Rex M for this bit of wisdom:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//https://*.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
});
}
找到所有用户的朋友后,我需要在 WPF 表单上显示他们。我有一个问题,并非所有用户都有至少 5 个朋友,有些甚至没有朋友!这是我所拥有的:
private void showUserFriends()
{
if (friendsList.ToList().Count > 0)
{
friend1.Source = new BitmapImage(new Uri(friendsList.ToList()[0].Photo));
label11.Content = friendsList.ToList()[0].Name;
friend2.Source = new BitmapImage(new Uri(friendsList.ToList()[1].Photo));
label12.Content = friendsList.ToList()[1].Name;
//And so on, two more times. I want to show 4 friends on the window.
}
}
所以这个问题有两个部分:
您建议我如何处理用户可能拥有的不同数量的朋友。使用我当前的代码,如果用户没有朋友,我会收到 IndexOutOfBounds 异常,因为 FriendsList[0] 不存在。
如何更有效地验证用户是否有朋友?调用 .ToList() 似乎很费力。
【问题讨论】:
标签: c# .net linq ienumerable