0

我目前有一个数组"Brand Products",我正在尝试根据name从数据库中获取它们后的字母顺序对其进行排序,该列表当前使用以下内容填充:

    protected override object[] GetCollection()
    {
        Brand brand = ItemLocator.LocateItem(this.Parent, typeof(Brand)) as Brand;

        ICriteria criteria = CoreHttpModule.Session.CreateCriteria(typeof(Product));
        criteria.Add(NHibernate.Expression.Expression.Eq("Brand", brand));
        criteria.Add(NHibernate.Expression.Expression.Eq("IsVisibleOnWebsite", true));

        IList<Product> productList = criteria.List<Product>();

        IList<Product> filteredLroductList = new List<Product>();

        for (int i = 0; i < productList.Count; i++)
        {
            if (productList[i].Parent != null)
            {
                filteredLroductList.Add(productList[i]);
            }
        }

        object[] filteredProductListArray = new object[filteredLroductList.Count];

        for (int i = 0; i < filteredLroductList.Count; i++)
        {
            filteredProductListArray.SetValue(filteredLroductList[i], i);
        }

             return filteredProductListArray;
    }
4

5 回答 5

2

您可以在单个 linq 表达式中实现它。

products[] productList = criteria.List<Product>()
                                  .Where(p => p.Parent != null)
                                  .OrderBy((p => p.Name)
                                  .ToArray();

完整的代码。

protected override object[] GetCollection()
{
    Brand brand = ItemLocator.LocateItem(this.Parent, typeof(Brand)) as Brand;

    ICriteria criteria = CoreHttpModule.Session.CreateCriteria(typeof(Product));
    criteria.Add(NHibernate.Expression.Expression.Eq("Brand", brand));
    criteria.Add(NHibernate.Expression.Expression.Eq("IsVisibleOnWebsite", true));

    products[] productList = criteria.List<Product>()
                                         .Where(p => p.Parent != null)
                                         .OrderBy((p => p.Name)
                                         .ToArray();
    return productList;
}
于 2012-10-19T11:08:24.060 回答
0

我只需将您方法的第二部分替换为:

return filteredProductList.OrderBy(f => f.BrandName).ToArray();

假设这BrandName是您要订购的

于 2012-10-19T11:04:23.653 回答
0

试试这个:

protected override object[] GetCollection()
{
    Brand brand = ItemLocator.LocateItem(this.Parent, typeof(Brand)) as Brand;

    ICriteria criteria = CoreHttpModule.Session.CreateCriteria(typeof(Product));
    criteria.Add(NHibernate.Expression.Expression.Eq("Brand", brand));
    criteria.Add(NHibernate.Expression.Expression.Eq("IsVisibleOnWebsite", true));

    return criteria.List<Product>()
        .Where(x => x.Parent != null)
        .OrderBy(x => x.Name)
        .Cast<object>()
        .ToArray();
}
于 2012-10-19T11:05:14.890 回答
0

大致是这样的,具体取决于您的类型:

var products = from p in GetCollection() orderby p.ProductName select p;

于 2012-10-19T11:06:03.153 回答
0

如果将其保留为列表,则可以对集合使用 linq ...

mylist = myList.OrderBy(x => x.Name).ToList();

于 2012-10-19T11:07:32.950 回答