在c#中尝试循环遍历List

时间:2014-08-12 10:23:27

标签: c# sql-server linq-to-sql

我试图在LINQ to SQL中循环select语句的结果并将结果插入表中。我使用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();
}

1 个答案:

答案 0 :(得分:2)

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

一般来说,如果你在C#中使用for循环,那么当你在foreach循环中有一种简单的方法时,你很可能会这么做:

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

可能是

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