gpt4 book ai didi

c# - 如何进行比嵌套循环更高效的 Entity Framework LINQ 调用

转载 作者:行者123 更新时间:2023-11-30 20:22:28 25 4
gpt4 key购买 nike

是否有更有效的方式来编写此 LINQ 语句?

功能使用与产品相同的模型(因为它们几乎相同)。

var products = db.Products.Where(q => q.IsFeature == false).ToList();
foreach (Product pr in products)
{
var features = db.Products.Where(q => q.ParentID == pr.ID).ToList();
foreach(Product feature in features)
{
pr.Features.Add(feature);
}
}

和模型:

    public class Product
{
//START
public Product()
{
Features = new HashSet<Product>();
}

public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool IsFeature { get; set; }
public int ParentID { get; set; }// If IsFeature is true we need to know its parent

//Nav Props
public ICollection<Product> Features { get; set; }// Features can be represented with the same model as product as they are almost identical
}

这满足了我的需要,即产品列表(Products),每个产品都有自己的功能列表(Features),但是否有更优雅/高效的替代方案?

最佳答案

您需要的是 join :

var productFeatures = 
db.Products.Where(q => !q.IsFeature)
.Join(db.Products, p => p.ID, f => f.ParentId, (p, f) => new { product: p, features: f.ToList() })
.ToList();

对于 db.Products.Where(q => !q.IsFeature) 中的每个对象这将找到每个 db.Products有一个 ParentId等于它的 ID字段。

结果将投影到 List() 中具有字段 product (Product) 的匿名类型和 features (List<Product>)

关于c# - 如何进行比嵌套循环更高效的 Entity Framework LINQ 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31539260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com