// 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);
我需要将每个SuperHeroModel(superHeros集合)中的Powers集合替换为powers集合中的匹配模型集合。
什么是一个很好的LINQ到对象的方法来将平坦的权力列表注入superHeros的层次结构?
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;
}
答案 0 :(得分:1)
这应该有效:
foreach (SuperHeroModel superHero in superHeros)
{
IEnumerable<int> powerIds = superHero.Powers.Select(p => p.PowerId);
superHeros.Powers = powers.Where(p => powerIds.Contains(p.PowerId));
}