0

我真的不知道如何解释这个问题。抱歉,如果它是重复的帖子。下面的代码可以正常工作。将 ID 为 1031 的产品返回给我,当我运行过滤器时(在哪里),我得到了相同的产品(因为这个产品在部门和类别中)。好的!但是当我删除 where 1031 (第二行代码)时,它不再起作用了。称为 GroupsID 的 IEnumerable 属性在(部门的)内部只有一个值。它很奇怪。当放置 where product.id == 1031 时,该属性有 2 个值(49 和 137),但是当我删除 where product.id==1031 时,它只返回每个产品的第一个组值(部门)。我列表中的所有产品都只有一个值(大多数情况下为 49)。

   model.Products = from product in context.Products
                        where product.ID == 1031
                        orderby Guid.NewGuid()
                        select new ProductViewModel()
                        {
                            ID = product.ID,
                            FullDescription = product.FullDescription,
                            FileName = (from image in product.ProductImages
                                        select image.FileName).FirstOrDefault(),
                            Price = (from priceList in product.PriceListProducts
                                    select priceList.Price).FirstOrDefault(),
                            GroupsID = (from related in product.ProductGroupRelateds
                                        select related.ProductGroup_ID)
                        };

    CategoryViewModel ctg = model.Categories.Where(categ => categ.FriendlyUrl.ToLower().Equals(filter.ToLower()) || categ.FriendlyUrl.ToLower().Equals(categoryURL.ToLower())).Select(categ => new CategoryViewModel() { ID = categ.ID, Name = categ.Name, FriendlyUrl = categ.FriendlyUrl, Index = categ.Index }).DefaultIfEmpty(null).First();
    if (ctg != null)
        model.Products = model.Products.Where(product => product.GroupsID.Contains(ctg.ID));

    DepartmentViewModel dpt = model.Departments.Where(depto => depto.FriendlyUrl.ToLower().Equals(filter.ToLower()) || depto.FriendlyUrl.ToLower().Equals(departmentURL.ToLower())).Select(depto => new DepartmentViewModel() { ID = depto.ID, Name = depto.Name, FriendlyUrl = depto.FriendlyUrl, Index = depto.Index }).DefaultIfEmpty(null).First();
    if (dpt != null)
        model.Products = model.Products.Where(product => product.GroupsID.Contains(dpt.ID));
4

1 回答 1

0

删除orderby Guid.NewGuid(). 一般来说,这不是洗牌的好方法,在某些情况下可能会破坏你的代码。以更好的方式实现您的 shuffle,例如,请参阅Is using Random and OrderBy a good shuffle algorithm?IEnumerable 上的扩展方法需要洗牌。简短的版本是您可以使用的代码:

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
    T[] elements = source.ToArray();
    for (int i = elements.Length - 1; i >= 0; i--)
    {
        // Swap element "i" with a random earlier element it (or itself)
        // ... except we don't really need to swap it fully, as we can
        // return it immediately, and afterwards it's irrelevant.
        int swapIndex = rng.Next(i + 1);
        yield return elements[swapIndex];
        elements[swapIndex] = elements[i];
    }
}
于 2013-04-19T20:01:32.683 回答