以下代碼會產生兩個項目。第一個項目包含一個Component
對象的列表。第二個項目還包含一個Component
對象的列表。在這個例子中,第二個列表應該是空的,因爲Component
列表沒有DishID=10
。我該如何解決這個問題?Linq無用列表
換句話說result[1].components.Count
應該是0。
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
List<Component> Component = new List<Component>();
List<Dish> Dish = new List<Dish>();
Dish.Add(new Dish { DishID = 9, CategoryID = 6, DishName = "Pork" });
Dish.Add(new Dish { DishID = 10, CategoryID = 6, DishName = "Beef" });
Component.Add(new Component { ComponentID = 1, DishID = 9, AmountID = "1", NameID = "1" });
List<Item> result = (from dishes in Dish
join components in Component on dishes.DishID equals components.DishID
into item
from p in item.DefaultIfEmpty()
select new { CategoryID = dishes.CategoryID, DishID = dishes.DishID, ComponentID = p != null ? p.ComponentID : default(int), DishName = dishes.DishName, AmountID = p != null ? p.AmountID : null, NameID = p != null ? p.NameID : null }).ToList().GroupBy(key => key.DishID)
.Select(g => new Item()
{
DishID = g.Key,
components = g.Select(t => new Component { AmountID = t.AmountID, ComponentID = t.ComponentID, DishID = t.DishID, NameID = t.NameID }).ToList()
})
.ToList();
}
}
public class Item
{
public int DishID { get; set; }
public List<Component> components { get; set; }
}
public partial class Component
{
public int ComponentID { get; set; }
public int DishID { get; set; }
public string AmountID { get; set; }
public string NameID { get; set; }
}
public partial class Dish
{
public int DishID { get; set; }
public int CategoryID { get; set; }
public string DishName { get; set; }
}
}
爲什麼downvoted? – A191919