首页 > 解决方案 > 从 Entity 中为不同的内部实体的属性值选择替代元素并重复它们

问题描述

我有一个Product包含实体的Category实体。现在我想要实现的是一个产品列表,其中列表包含产品,其中一个类别的产品应该在列出所有其他类别的产品后出现。例如:如果有三个类别(cat1、cat2 和 cat3)并且每个类别包含 2 到 3 个产品并且pageSize是 5,那么列表应该是这样的:

以下是我的代码。但它现在显示了正确的结果。

var randomProducts = new List<Product>();

var categories = Products.Select(c => c.Category.ID).Distinct().ToList();
int y = categories.First();
int index = 0;
for (int i = 0; i < pageSize; i++)
{
    if (index == categories.Count)
        break;
    var catid = categories[index];
    var _products = Products.Skip(skipCount).ToList().Except(randomProducts).Where(c => c.Category.ID == catid);
    if(_products != null && _products.Count() > 0)
        randomProducts.Add(_products.First());
    else
    {
        index++;
    }

    if (randomProducts.Count == Products.Count())
        break;
}
return randomProducts;

标签: c#.netasp.net-mvcentity-frameworkef-code-first

解决方案


推荐阅读