简体   繁体   中英

Updating List<string> values using linq C#

I have a list of strings that I would like to iterate through and change the values if certain items in the list if they match up to a string value in a separate list of objects.

User inputs an email address into an Event object that contains a list of EventMembers:

List<string> EventMembers

I would then like to check through all users in the database to find the username(e-mail address) that matches with the inputted e-mail address

i understand I cannot change values in a list using a foreach loop, but i'm lost with what to do with linq. Basically i'm trying to do something like this:

var allUsers = _userManager.Users
                    

                foreach (var a in allUsers)
                {
                    foreach (var e in @event.EventMembers)
                    {
                        if (e == a.UserName)
                        {
                            e = a.FirstName + a.LastName;
                        }
                    }
                }

The best thing would be to define an initial collection of members so you don't keep modifying the list while the foreach is still running. You could then check if EventMembers contain the username and then replace it by accessing the value with the index.

var allUsers = _userManager.Users;
List<string> Members;
foreach (var a in allUsers)
{
     if (@event.EventMembers.Contains(a.UserName))
     {
         var index = @event.Members.IndexOf(a.UserName);
         Members[index] = a.FirstName + a.LastName;
     }
}
EventMembers = Members;

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