查询子属性时选择父项和子项

时间:2015-11-03 10:54:11

标签: c# linq

在我的数据结构中,我有以下类:

public partial class Item
{
    // stuff
    public int QuoteId { get; set; }
    public virtual ItemType ItemType { get; set; }
}

public partial class ItemType
{
    //stuff
    public virtual ICollection<Item> Items { get; set; }
}

我想要做的是获取所有ItemTypes的列表,每个ItemTypes都根据QuoteId填充其Items集合。

因此,例如,如果有三种项目类型,则只有两种项目的报价标识为50:

  • ItemType1
    • Item.QuoteId == 50
  • ItemType2
  • ItemType3
    • Item.QuoteId == 50

我已经设法通过此查询获得了一些东西:

r.ItemTypes.Select(x => x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId));

但是这给了你(正如你所料,因为我Select在物品上)是IEnumerable<IEnumerable<Item>>。这具有我之前的结构,但没有ItemType数据。

我意识到这是一个愚蠢的问题,但我对无法得到答案感到沮丧。

3 个答案:

答案 0 :(得分:9)

r.ItemTypes.Where(x => x.Items.Any(i => i.QuoteId == CurrentQuote.QuoteId));

如果您需要获取所有ItemTypes并且只获取每个项目的特定项目,您可以这样做:

r.ItemTypes.Select(x => new 
{
    x, 
    FilteredItems = x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId)
});

之后,您需要为每个ItemType

分配x.ItemsFilteredItems

答案 1 :(得分:2)

如果您想要给定Item.ItemType的所有ItemType,则必须选择QuoteId属性。您还必须使用SelectMany来展平“嵌套”集合:

IEnumerable<ItemType> types = r.ItemTypes
    .SelectMany(x => x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId)
                            .Select(i => i.ItemType));

如果您对嵌套ItemType不感兴趣(不知道逻辑),可以使用Backs' approach

IEnumerable<ItemType> types = r.ItemTypes
    .Where(x => x.Items.Any(i => i.QuoteId == CurrentQuote.QuoteId));

答案 2 :(得分:0)

var result = from itemTypes in r.ItemTypes
             where itemTypes.QuoteId equals CurrentQuote.QuoteId
             select new {itemType = itemTypes}