为什么Linq在没有使用过滤器时只返回一个对象

时间:2013-04-19 19:38:34

标签: c# .net linq collections ienumerable

我真的不知道如何解释这个问题。对不起,如果它是重复的帖子。 以下代码可以罚款。给我回复ID为1031的产品,当我运行过滤器(在哪里)时,我得到相同的产品(因为这个是在部门和类别内)。好!但是,当我删除1031(seconde代码行)的地方时,它不再起作用了。名为GroupsID的IEnumerable属性在(部门)内只有一个值。这很奇怪。当放置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));

1 个答案:

答案 0 :(得分:0)

删除orderby Guid.NewGuid()。一般来说,这不是一个好的方式,而且在某些情况下会破坏你的代码。以更好的方式实施您的洗牌,例如请参阅Is using Random and OrderBy a good shuffle algorithm?An extension method on IEnumerable needed for shuffling。简短版本是您可以使用的代码:

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];
    }
}