// simple EF projection (anonymous type returned)
var superHerosData = from hero in filteredHeros
select new
{
hero.HeroId,
hero.FirstName
hero.LastName
Powers = from power in hero.Powers
select new
{
power.PowerId;
}
};
List<SuperHeroModel> superHeros = new List<SuperHeroModel>();
// populates superHeros (collection of SuperHeroModel) with the values in superHerosData
MapToModel(superHerosData, ref superHeros)
IQueryable<DAL.Models.Power> powersData = from hero in filteredHeros
from power in hero.Powers
select power;
如果在单个操作(平面集合)中完成,获取权力是昂贵的并且具有更好的性能
List<PowerModel> powers = await GetPowers(powersData);
我需要用 powers 集合中的匹配模型集合替换每个 SuperHeroModel(superHeros 集合)中的 Powers 集合。
将平面权力列表注入超级英雄层次结构的良好 LINQ-to-objects 方法是什么?
SuperHeroModel.Powers
当前包含PowerModel
仅填充 PowerId 的集合
更新:
像这样的东西可能会起作用,但感觉对 Linq 不太友好。我希望有一个更优雅的解决方案:
foreach (SuperHeroModel superHero in superHeros)
{
IEnumerable<int> superHeroPowerIds = superHero.Powers.Select(p => p.PowerId);
List<PowerModel> superHeroPowers = powers.Where(power => superHeroPowerIds.Contains(power.PowerId)).ToList();
superHero.Powers = superHeroPowers;
}