简体   繁体   English

更新列表<string>使用 linq C# 的值</string>

[英]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:用户将 email 地址输入到包含 EventMembers 列表的事件 object 中:

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.我知道我无法使用 foreach 循环更改列表中的值,但我不知道如何处理 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.最好的办法是定义成员的初始集合,这样您就不会在 foreach 仍在运行时继续修改列表。 You could then check if EventMembers contain the username and then replace it by accessing the value with the index.然后,您可以检查EventMembers是否包含用户名,然后通过使用索引访问值来替换它。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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