c#中尝试循环List

本文关键字:循环 List | 更新日期: 2023-09-27 18:17:31

我试图通过LINQ到SQL的选择语句的结果循环,并将结果插入到表中。我用一个for循环来做迭代,但它继续取第一个结果,不插入第二个值。这是我试过的。

//Get the admin info from AdminContactInfoViews table
var GetAdmin = (from ur in db.AdminContactInfoViews
                where ur.PropertyName == "Telephone" && ur.RoleName == Properties.Settings.Default.Admin
                select ur).ToList();

for (int i = 0; i < GetAdmin.Count; i++)
{
    Alert Notification = (from m in db.Alerts where m.Id == Properties.Settings.Default.NewUserRegistration select m).FirstOrDefault();
    string EmailText = Notification.Email.Replace("%RTSSAdmin%", GetAdmin.FirstOrDefault().Username);
    string SMSText = Notification.Sms.Replace("%RTSSAdmin%", GetAdmin.FirstOrDefault().Username);


    AlertNotification StoreEmail = new AlertNotification
    {
        Sender = Properties.Settings.Default.NoReplyEmail,
        Receiver = GetAdmin[i].Email,
        Subject = Notification.SubjectEmail,
        Message = EmailText,
        NotificationTypeId = Properties.Settings.Default.emailnotification,
        NotificationStatusId = 0,
        ModifiedBy = "SYSTEM",
        ModifiedDate = DateTime.Now,
        SentDate = DateTime.Now,
    };
    db.AlertNotifications.InsertOnSubmit(StoreEmail);
    db.SubmitChanges();
}

c#中尝试循环List

如果您有一个遍历列表的循环,则需要实际使用该循环索引的元素。GetAdmin[i]是正确的,GetAdmin.FirstOrDefault()是给你第一个,而不是电流。

一般来说,如果你在c#中使用for循环,你可能是在使用一种困难的方法,而有一种简单的方法,即foreach-loop:

for (int i = 0; i < GetAdmin.Count; i++)
{
  Console.WriteLine(GetAdmin[i]);
}
可能

foreach(var admin in GetAdmin)
{
  Console.WriteLine(admin);
}