I want to check the IEnumerable graph, but it is very small. Any help?

Special thanks to Rex M for this piece of wisdom :

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

After finding all the friends of the users, I need to show them in WPF form. I have a problem that not all users have at least 5 friends, some do not even have friends! Here is what I have:

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

So this question has two parts:

  • How do you suggest me handle the different number of friends that a user can have. With my current code, if the user has no friends, I get an IndexOutOfBounds exception because friendList [0] does not exist.

  • How can I handle checking if a user has friends more efficiently? Calling .ToList () seems very taxable.

+3
4

ToList() IEnumerable, , , . , " " - , ToList() IEnumerable, .

. IEnumerable ( Linq) , IEnumerable, , List .

.

List<Friend> friends = FindFriends().ToList();
//Then use the friends list....

, , - , , , ItemsControl, , , loop, .

List<Friend> friends = FindFriends().ToList();
if(friends.Count > 0)
{
  foreach(Friend f in friends)
  {
    //Create your Control(s) and add them to your form or panel controls container
    // somthing like (untested) myPanel.Controls.Add(new Label(){Text = f.Name});
  }
}
+1

1) ListBox. .

2) Any().

+3

ToList() if, .

, MVVM XAML

+2

Use some ItemContainer control like ItemsControl . You simply specify the template for which the element should look and set its property ItemsSource:

myItemsControl.ItemsSource = new ObservableCollection(myFriends.Take(4));

This will show up to 4 friends, repeating the pattern as many times as needed, but only 0 if the collection is empty.

+1
source

Source: https://habr.com/ru/post/1753459/


All Articles