将以下代码写入一些更好/更少的行时遇到一些麻烦:)有人有好的解决方案吗?//custom implementation for popular filters var popularFilter = new Dictionary<string, int>(); foreach (var car in allFilteredCars) { foreach (var offering in car.Offerings) { if (popularFilter.ContainsKey(offering)) popularFilter[offering] = popularFilter[offering] + 1; else popularFilter.Add(offering, 1); } } categories.Add(new Category { Name = "popular", Code = "popular", Values = popularFilter.Select(p => new Value { Code = p.Key, Name = p.Key, Count = p.Value }).ToList() });如果可能,我希望我直接将其添加到categories列表中。car.offerings = list<string>所以基本上是这样的:Categories.Add(allFilteredCars.SelectMany( c => c.Offerings.Select( o => new { something magical here} .Select(a => new Category{ code.. etc etc..} ));
2 回答
米脂
TA贡献1836条经验 获得超3个赞
看起来您只想执行 aSelectMany来获取产品,然后将它们分组并选择Count.
categories.Add(new Category
{
Name = "popular",
Code = "popular",
Values = allFilteredCars.SelectMany(c => c.Offerings)
.GroupBy(o => o)
.Select(grp => new Value
{
Code = grp.Key,
Name = grp.Key,
Count = grp.Count()
}).ToList()
});
达令说
TA贡献1821条经验 获得超6个赞
您的非 linq 代码看起来已经很不错了。您可以使用 GroupBy 和 ToDictionary 使用 linq 创建字典:
var dictionary = offerings
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
- 2 回答
- 0 关注
- 117 浏览
添加回答
举报
0/150
提交
取消