I have this object structure
public class Product
{
public int Id {get;set;}
public string DisplayName{get;set;}
public Ingredient[] Ingredents{get;set;}
}
public class Ingredient
{
public int id{get;set;}
public string Name{get;set;}
}
I have the datatable with the below result set
Id | DisplayName | IngredientId | IngName
-------------+-------------------------+------------------------
1 | Prod1 | 1 | Ing1
1 | Prod1 | 2 | Ing2
1 | Prod1 | 3 | Ing3
2 | Prod2 | 1 | Ing1
2 | Prod2 | 2 | Ing2
3 | Prod3 | 1 | Ing1
3 | Prod3 | 2 | Ing2
I need to have LINQ query which would give me list of Products as below: // pseudo code which describes structure:
resultProductList =
{
new Product() { Id = 1
, DisplayName = "Prod1"
, Ingredients = {
new Ingredient{ Id = 1, Name = "Ing1" }
, new Ingredient{ Id = 2, Name = "Ing2" }
, new Ingredient{ Id = 3, Name = "Ing3" }
}
, new Product() { Id = 2
, DisplayName = "Prod2"
, Ingredients = {
new Ingredient{ Id = 1, Name = "Ing1" }
, new Ingredient{ Id = 2, Name = "Ing2" }
}
, new Product() { Id = 3
, DisplayName = "Prod3"
, Ingredients = {
new Ingredient{ Id = 1, Name = "Ing1" }
, new Ingredient{ Id = 2, Name = "Ing2" }
}
}
I refered this but I am unable to get the solution.
List<Product> lstContracttype = dsGetProducts.Tables[0]
.AsEnumerable()
.Select(x => new Product
{
Id= Convert.ToInt32(x[0]),
DisplayName= Convert.ToString(x[1])
})
.GroupBy(y => y.id).ToList();
Could anyone please suggest how could I write LINQ query for get this result?
UPDATE: I added one more sub-class and added it to main Product class. See below:
public class Product
{
public int Id {get;set;}
public string DisplayName{get;set;}
public Ingredient[] Ingredents{get;set;}
public Price MyPrice{get;set;}
}
public class Price
{
public int min {get;set;}
public int max {get;set;}
public int defaultPrice {get;set;}
}
I modified the LINQ query as follows and am getting the results.
My question is in below LINQ query, should I write .First<Price> or .FirstOrDefault<Price>?
Is this proper way to handle this condition or is there any other way?
var lstProducts = dsGetProducts.Tables[0].AsEnumerable().Cast<DataRow>()
.GroupBy(r => new { Id = r["Id"],
DisplayName = r["DisplayName"],
priceMax = r["priceMax"],
priceMin = r["priceMin"],
priceDefault = r["priceDefault"]
})
.Select(g => new Product()
{
Id = (int)g.Key.Id,
DisplayName = (string)g.Key.DisplayName,
Ingredients = g.Select(r => new Ingredient()
{
id = (int)r["IngredientId"],
Name = (string)r["IngName"]
}).ToArray(),
MyPrice = g.Select(r => new Price()
{
min= (int)r["minPrice"],
max= (int)r["maxPrice"],
defaultPrice= (int)r["priceDefault"],
}).FirstOrDefault<Price>()