【问题标题】:how seed method use foreach loop?种子方法如何使用foreach循环?
【发布时间】:2014-07-08 14:33:15
【问题描述】:
 protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
  {
      var students = new List<Student>
        {
            new Student { FirstMidName = "Carson",   LastName = "Alexander", 
                EnrollmentDate = DateTime.Parse("2010-09-01") },
            new Student { FirstMidName = "Meredith", LastName = "Alonso",    
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Arturo",   LastName = "Anand",     
                EnrollmentDate = DateTime.Parse("2013-09-01") },
            new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Yan",      LastName = "Li",        
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Peggy",    LastName = "Justice",   
                EnrollmentDate = DateTime.Parse("2011-09-01") },
            new Student { FirstMidName = "Laura",    LastName = "Norman",    
                EnrollmentDate = DateTime.Parse("2013-09-01") },
            new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
                EnrollmentDate = DateTime.Parse("2005-08-11") }
        };
     students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
     context.SaveChanges();

我在我的 MVC 项目中使用迁移,但在上面代码的 Configuration.cs 文件中。使用种子方法,但我不明白 Foreach 循环的语法。所以任何人都可以建议我。

【问题讨论】:

  • 这是ForEach 而不是foreach。它是List.ForEach 而不是一般的foreach 迭代语句。
  • 重写,那行代码将是foreach(var s in students)

标签: c# asp.net-mvc entity-framework


【解决方案1】:

List.ForEach 方法类似于“foreach”循环。它使用 lambda 对每个元素执行操作。

http://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/bb397687.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多