2013-03-24 58 views
2

我在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; } 
} 

我想與「AA」,「BB」的應用程序名稱插入一些記錄和使用類似下面的「XX」:

List<Application> applications; 

public void seedData() { 
    var a = new Application { Name = "xx" }; 
    applications.Add(a); 
} 

有沒有一種方式,我可以附上對於 循環創造了一個新的應用程序記錄的線,並有那麼序列通過並插入三個應用程序,而不是我 編碼他們一個接一個。

回答

6

您可以使用LINQ此:

var names = new[] {"A", "B", "C"}; 
var apps = names.Select(x => new Application { Name = x }); 
applications.AddRange(apps); 
3

如果我理解正確的問題,那麼你的seedData()方法可能是這個樣子:

public void seedData() 
{ 
    const string[] names = new string[] { "xx", "bb", "xx" }; 
    foreach (string name in names) 
     applications.Add(new Application { Name = name }); 
} 
1

如果你想用一個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); 
} 
2

您可以使用object or collection initializers

List<Application> applications = new List<Application>() 
{ 
    new Application(){Name="aa"}, 
    new Application(){Name="bb"}, 
    new Application(){Name="xx"} 
}; 

無需將應用程序名稱存儲在單獨的數組中,並循環對其進行初始化。
我認爲結果代碼更清晰。

1

您可以使用:

public static IList<Application> CreatesApp(IEnumerable<string> names) 
    { 
     return names == null ? new List<Application>() : 
      names.Select(name => new Application() { Name = name }).ToList(); 
    } 
0

使用線程。和。加入

前 創建它創建線程,並返回它的基準的函數 即:createAppThread(應用程序)

所以 您的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線程一段時間,但它會工作。