C# 如何使用LINQ在类内填充集合?
我有以下资料:C# 如何使用LINQ在类内填充集合?,c#,linq,C#,Linq,我有以下资料: foreach (string applicationName in applicationNames) { _uow.Applications.Add( new Application { Name = applicationName, ModifiedDate = DateTime.Now, TestAccounts = (from t
foreach (string applicationName in applicationNames)
{
_uow.Applications.Add(
new Application
{
Name = applicationName,
ModifiedDate = DateTime.Now,
TestAccounts = (from testAccountName in testAccountNames
select new TestAccount
{
Name = testAccountName ,
ModifiedDate = DateTime.Now
})
});
}
问题是,它在select上的VS2012 IDE中给了我一个错误。这里写着:
Error 3 Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Relational.Models.TestAccount>' to
'System.Collections.Generic.ICollection<Relational.Models.TestAccount>'.
An explicit conversion exists (are you missing a cast?
错误3无法隐式转换类型
“System.Collections.Generic.IEnumerable”到
“System.Collections.Generic.ICollection”。
存在显式转换(是否缺少强制转换?
下面是应用程序类:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public virtual byte[] Version { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
公共部分类应用程序
{
公共应用程序()
{
this.TestAccounts=新列表();
}
public int ApplicationId{get;set;}
公共字符串名称{get;set;}
公共虚拟字节[]版本{get;set;}
public System.DateTime ModifiedDate{get;set;}
公共虚拟ICollection测试帐户{get;set;}
}
使用:
您需要对IList进行强制转换
{
名称=应用程序名称,
ModifiedDate=DateTime。现在,
TestAccounts=(来自testAccountName中的testAccountName
选择NewTestAccount
{
名称=testAccountName,
ModifiedDate=DateTime.Now
}).ToList()//的可能重复项
foreach (string applicationName in applicationNames)
{
_uow.Applications.Add(
new Application
{
Name = applicationName,
ModifiedDate = DateTime.Now,
TestAccounts = (from testAccountName in testAccountNames
select new TestAccount
{
Name = testAccountName ,
ModifiedDate = DateTime.Now
}).ToList()
});
}
{
Name = applicationName,
ModifiedDate = DateTime.Now,
TestAccounts = (from testAccountName in testAccountNames
select new TestAccount
{
Name = testAccountName ,
ModifiedDate = DateTime.Now
}).ToList() // <-- try this
});