[英]How can I return the contents of a collection inside a class using LINQ?
我有以下課程:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
public partial class TestAccount
{
public TestAccount()
{
this.Subjects = new List<Subject>();
}
public int TestAccountId { get; set; }
public string Name { get; set; }
public int ApplicationId { get; set; }
}
在我的代碼中,我有以下代碼返回一條記錄的IQueryable<Application>
。
var applications = DbSet.Where(a => a.ApplicationId == applicationId)
我如何更改它以便它返回: ICollection<TestAccount>
當您收到一個Application
序列並且想要一個TestAccount
序列時,可以在Application
TestAccounts
屬性中找到該序列,您應該使用SelectMany
LINQ方法來整理序列。 嘗試使用下一個代碼段:
DbSet.Where(a => a.ApplicationId == applicationId)
.SelectMany(app => app.TestAccounts)
.ToList();
它將返回所有TestAccounts
的列表,該列表收集在您的內部
IQueryable<Application>
。
ToList
將數據帶入內存,並將其分配給ICollection<T>
接口( List<T>
實現ICollection<T>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.