需要 foreach 到 linq 表达式的帮助

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


有人有好的解决方案吗?


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

  ));


拉莫斯之舞
浏览 125回答 2
2回答

米脂

看起来您只想执行 aSelectMany来获取产品,然后将它们分组并选择Count.categories.Add(new Category{&nbsp; &nbsp; Name = "popular",&nbsp; &nbsp; Code = "popular",&nbsp; &nbsp; Values = allFilteredCars.SelectMany(c => c.Offerings)&nbsp; &nbsp; &nbsp; &nbsp; .GroupBy(o => o)&nbsp; &nbsp; &nbsp; &nbsp; .Select(grp => new Value&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Code = grp.Key,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = grp.Key,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Count = grp.Count()&nbsp; &nbsp; &nbsp; &nbsp; }).ToList()});

达令说

您的非 linq 代码看起来已经很不错了。您可以使用 GroupBy 和 ToDictionary 使用 linq 创建字典:var dictionary = offerings&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GroupBy(x => x)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToDictionary(x => x.Key, x => x.Count());
打开App,查看更多内容
随时随地看视频慕课网APP