[英]Trying to understand my IEnumerable and why I can't use .ToList()
我目前對我的一種數據對象回購模式有以下方法:
public async Task<IEnumerable<DropDownList>> GetDropDownListNoTracking()
{
return await context.TouchTypes
.AsNoTracking()
.Where(s => s.IsActive)
.Select(s => new DropDownList()
{
Id = s.Id,
Name = s.Description
}).ToListAsync();
}
當我在頁面視圖中調用它時:
private IList<DropDownList> TouchTypeList { get; set; }
private async Task LoadDropDownAsync()
{
TouchTypeList = await _unitOfWork.TouchType.GetDropDownListNoTracking();
}
我試圖理解為什么我不能只做GetDropDownListNoTracking().ToList()
而是要我投射: (IList<DropDownList>)
。
我可以輕松地更改屬性來解決這個問題,但我認為.ToList
可以在這里工作嗎?
我主要是想理解這一點,以便我能以正確的方式做到這一點。
GetDropDownListNoTracking
返回Task<IEnumerable<DropDownList>>
,而不是IEnumerable<DropDownList>
,所以你必須這樣做:
private async Task LoadDropDownAsync()
{
TouchTypeList = (await _unitOfWork.TouchType.GetDropDownListNoTracking()).ToList();
}
對一個您知道實際上總是列表的可枚舉調用ToList
會浪費 CPU 周期,並且表明您的方法的返回類型選擇不當。 最簡單的解決方案是將您的方法更改為:
public async Task<IList<DropDownList>> GetDropDownListNoTracking()
{
return await context.TouchTypes
.AsNoTracking()
.Where(s => s.IsActive)
.Select(s => new DropDownList()
{
Id = s.Id,
Name = s.Description
}).ToListAsync();
}
雖然我個人會改用IReadOnlyList
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.