使用Lambda表达式按计数排序不同的值

时间:2017-01-17 06:35:24

标签: entity-framework asp.net-mvc-4 lambda

我试图按计数从降序中选择不同的主要类别。但是得到以下错误:

  

DbExpressionBinding需要一个带有ResultType集合的输入表达式。

     

参数名称:输入

这是我的代码:

var Categories = products.Where(p => p.IsActive == true)
    .Select(n => n.MainCategory).Distinct().ToArray().OrderByDescending(p => p.Count());
if (Categories != null)
{
    int j = 0;
    foreach (var Category in Categories)
    {
        j++;
        var brands = products.Where(p => p.IsActive == true && p.MainCategory == Category && p.Brand != string.Empty && p.Brand != null).Select(n => n.Brand).Distinct().ToArray();
        if (brands == null || brands.Length == 0)
        {
            sb.AppendFormat("<li><a href=\"/hi-fi/{1}\" class=\"list-group-item list-group-item-success colordiv\">{0}</a><a href=\"#demo{2}\" data-toggle=\"collapse\" data-parent=\"#MainMenu\" class=\"glyphicon glyphicon-minus minus\"></a>\n", Category, Category.Replace(" ", "-"), j);
        }
        else
        {
            //code to list brands}
        }
    }
}

请指导我。

1 个答案:

答案 0 :(得分:0)

你应该阅读这个链接https://msdn.microsoft.com/en-us/library/bb548916(v=vs.110).aspx
我认为下面的代码可以满足您的需求。

public class MainCategory
{
    public IEnumerable<string> Datas { get; set; }
}

public class SpecialComprarer : IComparer<MainCategory>
{
    public int Compare(MainCategory x, MainCategory y)
    {
        if (x.Datas.Count() == y.Datas.Count())
            return 0;
        else if (x.Datas.Count() > y.Datas.Count())
            return 1;
        else
            return -1;
    }
}    

你可以像下面那样

List<MainCategory> db = new List<MainCategory> {

        new MainCategory { Datas = new List<string> { "1", "2", "3" } },
        new MainCategory { Datas = new List<string> { "1", "2", "3", "4" } },
        new MainCategory { Datas = new List<string> { "1", "2", "3", "4", "5" } },
        new MainCategory { Datas = new List<string> { "1", "2", "3", "4", "5", "6" } }
         };
        List<MainCategory> x = db.OrderByDescending(m => m, new SpecialComprarer()).ToList();  
相关问题