Рow 得到 2 到 4 个对象元素
本文关键字:对象 元素 ow 得到 | 更新日期: 2023-09-27 18:31:02
我从行有错误
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);
您使用计数作为字典的键,这意味着每当碰巧找到两个具有相同计数的类别时,您都会抛出该异常。
如果我理解您要正确执行的操作,则应将"业务类别"作为字典的键,并将计数作为值。
例如
Dictionary<string, int> viewBusinesAndCountLeft = grptemp.Take(4).ToDictionary(x => x.BusinessCategoryName, x => x.Count);
声明Dictionary<T,U>
表示具有 T 类型键的字典(在本例中为 int
) - 字典中的键必须是唯一的。
您可能希望键是字符串,值是计数。尝试切换参数:
Dictionary<string, int> viewBusinesAndCountLeft =
grptemp.Take(4).ToDictionary(x => x.BusinessCategoryName, x => x.Count);