0

I unable to come up with a linq query for the following scenario.

public class Product
{
    public virtual string ProductName { get; set; }
    public virtual IList<SubProduct> SubProducts { get; set; }
}

public class SubProduct
{
    public string SubProductName { get; set; }

    public int SubProductTypeId { get; set; }
}

public class SubProductType
{
    public int SubProductTypeId{ get; set; }
    public string Description { get; set; }
}

var productList = List<Product>();

var subProductTypeLlist = List<SubProductType>();

I have a list of products and each product has list of SubProducts. I want to get the query to represent {ProductName, Description}. Please suggest how to write linq query.

1 Answer 1

1

Something like this should do the trick:

var result = productList
    .SelectMany(p => p.SubProducts
        .Select(sp => new { SubProduct = sp, ProductName = p.ProductName }))
    .Select(sp => 
        new { Description = subProductTypeList
            .Single(spt => spt.SubProduct.SubProductTypeId == sp.SubProductTypeId).Description,
            ProductName = sp.ProductName })

In the SelectMany, we first do a Select on the internal IEnumerable (IList implements IEnumerable) to convert each SubProduct object to an anonymous class holding the SubProduct object and the ProductName. The SelectMany then converts that to a flat list. We then use Select on that list to create a new anonymous class again, where this time, we grab the Description from subProductTypeList. The result is an IEnumerable of an anonymous class with the members Description and ProductName.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your quick reply and help. I modified results query as per my need & now working. var products = new List(); var subProductTypeList = new List(); var typeListMap = subProductTypeList.ToDictionary(x => x.SubProductTypeId, x => x.Description); var results = productList.SelectMany(p => p.SubProducts, (t, i) => new { ProductName = t.ProductName, Description = typeListMap[i.SubProductTypeId] }).ToList();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.