0

我有错误

Dictionary<int, string> viewBusinesAndCountLeft = grptemp.Take(4).ToDictionary(x => x.Count, x => x.BusinessCategoryName);

错误:“已添加具有相同键的元素。”

这个怎么做?

var grptemp = (from adsBusines in m_adsRepository.SaleBusinesAds
               group adsBusines by adsBusines.BusinessCategory.Name
               into grp
               select new
               {
                  BusinessCategoryName = grp.Key,
                  Count = grp.Select(x => x.BusinessCategory.ChildItems.Count()).Distinct().Count()
               }).Take(8);

Dictionary<int, string> viewBusinesAndCountLeft = grptemp.Take(4).ToDictionary(x => x.Count, x => x.BusinessCategoryName);
Dictionary<int, string> viewBusinesAndCountRigth = grptemp.Skip(4).Take(4).ToDictionary(x => x.Count, x => x.BusinessCategoryName);
4

2 回答 2

1

您正在使用计数作为字典的键,这意味着每当您碰巧找到具有相同计数的两个类别时,您都会抛出该异常。

如果我理解您要正确执行的操作,则应该将“业务类别”作为字典的键,将计数作为值。

例如

Dictionary<string, int> viewBusinesAndCountLeft = grptemp.Take(4).ToDictionary(x => x.BusinessCategoryName, x => x.Count);
于 2012-04-12T06:47:49.443 回答
0

声明 aDictionary<T,U>表示具有 T 类型键的字典(在本例中为int) - 字典中的键必须是唯一的。

您可能希望键是字符串,值是计数。尝试切换你的论点:

Dictionary<string, int> viewBusinesAndCountLeft = 
    grptemp.Take(4).ToDictionary(x => x.BusinessCategoryName, x => x.Count);
于 2012-04-12T06:48:44.947 回答