[英]How can I seed data in a for loop with C#
I have the following class in C#: 我在C#中有以下课程:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
I would like to insert a few records with the application names of "aa", "bb" and "xx" using something like the following: 我想使用以下内容插入一些应用程序名称为“aa”,“bb”和“xx”的记录:
List<Application> applications;
public void seedData() {
var a = new Application { Name = "xx" };
applications.Add(a);
}
Is there a way that I can enclose the line that creates a new Application record in a for loop and have it then sequence through and insert the three applications rather than me coding them one by one. 有没有办法可以在for循环中包含创建新应用程序记录的行,然后让它顺序通过并插入三个应用程序而不是我逐个编写它们。
You can use LINQ for this: 您可以使用LINQ:
var names = new[] {"A", "B", "C"};
var apps = names.Select(x => new Application { Name = x });
applications.AddRange(apps);
If I understand the question correctly, then your seedData()
method could look something like this: 如果我正确理解了这个问题,那么你的
seedData()
方法看起来像这样:
public void seedData()
{
const string[] names = new string[] { "xx", "bb", "xx" };
foreach (string name in names)
applications.Add(new Application { Name = name });
}
You can use object or collection initializers 您可以使用对象或集合初始值设定项
List<Application> applications = new List<Application>()
{
new Application(){Name="aa"},
new Application(){Name="bb"},
new Application(){Name="xx"}
};
no need to store the app names in a separate array and loop over it to initialize. 无需将应用程序名称存储在单独的数组中,并在其上循环以进行初始化。
I think also that the resulting code is more clear. 我认为结果代码也更清晰。
If you would like to use a for
loop, here is one way to do this: 如果你想使用
for
循环,这是一种方法:
var names = new List<string>(new string[] { "aa", "bb", "xx" });
for(int i = 0; i < 3; i++)
{
var a = new Application { Name = names[i] };
applications.Add(a);
}
You can use: 您可以使用:
public static IList<Application> CreatesApp(IEnumerable<string> names)
{
return names == null ? new List<Application>() :
names.Select(name => new Application() { Name = name }).ToList();
}
Use threads. 使用线程。 and .join
和.join
ex create a function which creates thread and returns its reference ie: createAppThread(Application app) ex创建一个创建线程并返回其引用的函数,即:createAppThread(Application app)
so your for loop can be 所以你的for循环可以
//code from Cuong Le's answer
names = new[] {"A", "B", "C"};
for (int i=0;i<names.length();i++){
Application app=new Application { Name = "xx" };//create your app object
Thread th = createAppThread(app);
Thread.join(th);
}
this method may block the ui thread for some time but it will work. 这个方法可能会阻塞ui线程一段时间,但它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.