在Lambda Expression中使用Distinct并在foreach循环中使用它

时间:2016-12-03 05:49:22

标签: c# asp.net-mvc lambda

在这里,我试图首先获得唯一的主要类别名称,根据该主要类别中的可用品牌以及该特定品牌和主要类别的子类别。但不同的是不起作用并返回所有值。这是模型的代码。

public MvcHtmlString Submenu()
        {
            var products = _db.Products;
            var sb = new StringBuilder();

                sb.Append("<ul>");
                var mainmenu = products.Select(p => p.MainCategory).Distinct();
            if(mainmenu!= null)
            {
                int i = 0;
                foreach (var prods in products)
                {
                    i++;
                    sb.AppendFormat("<li><a  class=\"main-link\" href=\"#\">{0}</a>\n", prods.MainCategory);
                    var brans = products.Where(p => p.MainCategory == prods.MainCategory).Select(p => p.Brand).Distinct();
                    if (brans != null)
                    {
                        int j = 0;
                        foreach (var prodss in products)
                        {
                            j++;
                            sb.Append("<ul>");
                            sb.AppendFormat("<li><a  class=\"main-link\" href=\"#\">{0}</a>\n", prodss.Brand);
                            //var subCats = _db.Products.SqlQuery("Select Distinct(SubCategory) from Product where MainCategory = '" + mainmenu + "' && Brand = '"+brans+"'");
                            var subCats = products.Where(p => p.MainCategory == prods.MainCategory && p.Brand == prodss.Brand).Select(p => p.SubCategory).Distinct();
                            if (subCats != null)
                            {
                                int k = 0;
                                foreach (var pods in products)
                                {
                                    k++;
                                    sb.Append("<ul>");
                                    //sb.AppendFormat("<li><a   href=\"#\">{0}</a></li>\n", pods.SubCategory);
                                    sb.Append("</ul>");
                                }
                            }
                            sb.Append("</li>");
                            sb.Append("</ul>");
                        }
                    }
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");
            return new MvcHtmlString(sb.ToString());
        }

请指导我

1 个答案:

答案 0 :(得分:0)

您需要覆盖Product类的Equals和GetHashCode,但我想您只想通过产品的名称或ID来区分,所以您可以尝试这种extenssion方法:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> that, Func<TSource, TKey> selector)
{
    var set = new HashSet<TKey>();
    foreach (var element in that)
    {
        if (set.Add(selector(element)))
        {
            yield return element;
        }
    }
}