简体   繁体   中英

c# and Lists: How do I use the foreach loop to retrieve the objects form my list?

this is quite the nooby questions, it's just that I havn't been doing this for a long time and would need some help.

So here is the problem. I have this debug info on my list "lstfriendlist": 在此处输入图片说明

I simply put up a breakpoint in my activity, then clicked on my list and saw, that all my "friends" are brought to me on this list under "friendUsername".

I was able to retrieve a certain username via:

        string temp = lstfriendList[11].friendUsername.ToString(); 

This returns "torben" on my string "temp".

Now I just forgot how to use the foreach loop to retrieve all objects in order from my list and then write them down. I'm sorry to bother you with this, but I simply forgot :(

I hope you can help me. Thank you :)

You already have declared a variable of the type "Friend" in the foreach loop's head. Now you can access the properties of the current object by typing

foreach (Friend f in lstfriendList)
{
    string temp = f.friendUsername;
}

To complete Sebastian Hofmann answer, you can use .OrderBy or .OrderByDescending to order on name or username

foreach (Friend f in lstfriendList.OrderBy(list => list.friendUsername))
{
    string temp = f.friendUsername;
}

Will return user name from a to z

foreach (Friend f in lstfriendList.OrderByDescending(list => list.friendUsername))
{
    string temp = f.friendUsername;
}

Will return username z to a

I think there is no way to stuck there, since you are now having the Friend object( f ) with you inside the loop, just place a . after f and see what intellisense suggests, Anyway It is pretty good if you modify the class like the following, with override ToString() :

class Friend
{
    public string friendUsername { get; set; }
    public int friendId { get; set; }
    // Add rest of properties here
    public override string ToString()
    {
        return "ID :" + friendId +  "\n Friend Name: " + friendUsername;
        // Append rest of properties here
    }
}

And then use like this:

foreach (Friend f in lstfriendList)
{
    string friendDetails = f.ToString();
    Console.WriteLine(friendDetails);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM