C# 如何使用C在for循环中播种数据
我有以下C类课程:C# 如何使用C在for循环中播种数据,c#,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
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; }
}
我想插入几个应用程序名为aa、bb和xx的记录,使用类似于以下内容:
List<Application> applications;
public void seedData() {
var a = new Application { Name = "xx" };
applications.Add(a);
}
是否有一种方法可以将创建新应用程序记录的行括在for中
循环,然后让它依次插入这三个应用程序,而不是我
一个接一个地编码 您可以使用LINQ进行以下操作:
var names = new[] {"A", "B", "C"};
var apps = names.Select(x => new Application { Name = x });
applications.AddRange(apps);
如果我正确理解了这个问题,那么您的seedData方法可能如下所示:
public void seedData()
{
const string[] names = new string[] { "xx", "bb", "xx" };
foreach (string name in names)
applications.Add(new Application { Name = name });
}
如果要使用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);
}
你可以用
无需将应用程序名称存储在单独的数组中,并在其上循环以进行初始化。
我还认为生成的代码更清晰。您可以使用:
public static IList<Application> CreatesApp(IEnumerable<string> names)
{
return names == null ? new List<Application>() :
names.Select(name => new Application() { Name = name }).ToList();
}
使用线程。还有,加入
前
创建一个函数,该函数创建线程并返回其引用
ie:createAppThreadApplication应用程序
所以
您的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);
}
此方法可能会在一段时间内阻止ui线程,但它会起作用
//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);
}