繁体   English   中英

foreach到linq表达需要帮助

[英]foreach to linq expression help needed

在将以下代码编写到一些更好/更少的行时遇到麻烦:)

任何人都有好的解决方案?

//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..}
  ));

看来您只想执行SelectMany来获取产品,然后将它们分组并选择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()
});

您的非linq代码已经看起来不错。 您可以使用GroupBy和ToDictionary使用linq创建字典:

var dictionary = offerings
                .GroupBy(x => x)
                .ToDictionary(x => x.Key, x => x.Count());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM