2
// 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;
}
4

1 回答 1

1

这应该有效:

foreach (SuperHeroModel superHero in superHeros)
{
    IEnumerable<int> powerIds = superHero.Powers.Select(p => p.PowerId);
    superHeros.Powers = powers.Where(p => powerIds.Contains(p.PowerId));
}
于 2013-10-10T17:32:44.547 回答