c# - 如何使用 LINQ 填充类中的集合?

标签 c# linq

我有以下内容:

     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 
                           })
        });
     }

这个问题是它在 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?

这是应用程序类:

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

最佳答案

使用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()
    });
 }

关于c# - 如何使用 LINQ 填充类中的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15624012/

相关文章:

c# - Linq Orderby 与 SQL Orderby

c# - Linq to SQL Left Join、Order 和 Group By Count

c# - 计算具有相同项目数的多个 IEnumerable 的平均值

c# - 如何读取字节和字符串的混合文件

c# - 同一属性的不同 getter 和 setter 接口(interface)

c# - 为什么 NaN(不是数字)仅适用于 double ?

c# - 是否有用于访问Excel文件的免费API?

c# - 无法将重复行添加到 asp.net 表控件

c# - 动态 LINQ - 无法在 GUID 和字符串之间转换

c# - Entity Framework 返回 null 子项,底层 SQL 没问题