0

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;
                        }
                    }
                }
1
  • Don't do it with LINQ, just use a for loop. Normal LINQ won't work as you will get "Collection Changed" exceptions. Commented Feb 12, 2021 at 1:55

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. I didnt need to define an initial collection. I just used the code inside the If block and it works just fine. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.