My code is very small, not knowing about this simple use of Linq?

I have the following method, which is to parse the information from the XML response and return a collection of users.

I decided to create a Friend class and return the list to the calling method.

Here is what I have so far, but I noticed that the ids.ToList () method. Count parses each individual id element in a List, and then repeats it in a conditional expression. It is just super inefficient. I need help solving this problem because I'm not so good at Linq. Thank!

        public List<Friend> FindFriends()
        {
            List<Friend> friendList = new List<Friend>();

            var friends = doc.Element("ipb").Element("profile").Element("friends").Elements("user");
            var ids = from fr in friends
                      select fr.Element("id").Value;

            var names = from fr in friends
                        select fr.Element("name").Value;

            var urls = from fr in friends
                        select fr.Element("url").Value;

            var photos = from fr in friends
                        select fr.Element("photo").Value;

            if (ids.ToList().Count > 0)
            {
                for (int i = 0; i < ids.ToList().Count; i++)
                {
                    Friend buddy = new Friend();
                    buddy.ID = ids.ToList()[i];
                    buddy.Name = names.ToList()[i];
                    buddy.URL = urls.ToList()[i];
                    buddy.Photo = photos.ToList()[i];

                    friendList.Add(buddy);
                }
            }            

            return friendList;
        }
+1
source share
2 answers

- List<Friend>? IEnumerable<Friend> ? , :

IEnumerable<Friend> FindFriends()
{
    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
    });
}

, , , Friend, , , foreach IEnumerable. " ".

: <user> XML- . , XML- .

@anon, List<Friend> - , , .ToList() return. , , , .

+10

ids/names/urls/photos? . ToList(), .

List<Friend> friendList = (from f in doc.Element("ipb").Element("profile").Element("friends").Elements("user")
                          select new Friend() { 
                                                 ID = f.Element("id").Value, 
                                                 Name = f.Element("name").Value,
                                                 URL = f.Element("url").Value,
                                                 Photo = f.Element("photo").Value
                                 }).ToList();

return friendList;
0

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


All Articles