这是获取Linq上递归earch列表的最佳方法。
例如,如果我有一个可以将其他类别作为子类别的类别类,并且类别将产品作为其子项,则类似
Category1 > Product1
> Product2
Category2 > Product3
> Category21 > Product31
> Product32
> Product4
依此类推,我需要在列表中返回al类别和产品的ID。有没有办法实现这个目标?
答案 0 :(得分:1)
首先,在您的情况下,模型应如下所示:
public class Product
{
public int id { get; set; }
public string name { get; set; }
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
}
public class Category
{
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual Category Parent { get; set; }
public int? ParentID { get; set; }
private List<int> GetIds(Category category)
{
var list = Products == null ? new List<int>() : Products.Select(x => x.id).ToList();
if (Categories != null)
Categories.ToList().ForEach(x => {
list.Add(x.id);
list.AddRange(x.GetIds(x));
}
);
return list;
}
public List<int> GetIds()
{
return GetIds(this);
}
}
你将以这种方式执行它:
var db = new DataContext();
//switching on "LazyLoading" is extremely necessary
db.Configuration.LazyLoadingEnabled = true;
var first = db.Categories.Where(x => x.id == 5).First();
var ids = first.GetIds();