I've tried to decipher how to do this myself but my understanding of LINQ usage is pretty limited. What I have is two classes as such:
public class Grocery
{
public string ItemName { get; set; }
public List<ItemType> ItemTypes { get; set; }
}
public class ItemType
{
public double Weight { get; set; }
public long Quantity { get; set; }
}
The idea being you can have a Grocery object with ItemName "Carrots", and that comes in two different ItemTypes, e.g. where Weight = 1lb and where Weight = 2lb, with different quantities of each. Obviously there will be many more items than just carrots, and these are stored in a list also:
List<Grocery> groceries;
What I'd like to do is get a list of all quantities for all groceries, given a certain weight. E.g. I could do it like this for all items that have a 1lb type:
List<long> quantities = new List<long>();
foreach (Grocery grocery in groceries)
{
foreach (ItemType itemType in grocery.ItemTypes)
{
if (itemType.Weight == 1)
{
quantities.Add(itemType.Quantity);
}
}
}
What I would like to know is how I can achieve the same result using a LINQ expression, though I'm not sure if this is possible without reverting to using .ForEach and simply doing the same as the code above but in a less verbose (and therefore less readable) way. Appreciate your help.