【问题标题】:Avoid Repeating Group by Linq in C#避免在 C# 中通过 Linq 重复分组
【发布时间】:2014-09-19 18:32:01
【问题描述】:

我需要优化我的代码。我有一些重复代码。但我想优化它。谁能帮我优化我的代码。我怎样才能为此增加通用功能???

 foreach (var item in hotellocation.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count()))
            {
                if (item.Key != "")
                {
                    lstHotelLocation.Add(new HotelLocation()
                        {
                            Name = item.Key,
                            count = item.Value
                        });
                }
            }

            //need to Apply to linq

            foreach (var item in hoteltype.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count()))
            {               
                if (item.Key != "")
                {
                    lstHotelType.Add(new HotelTypeFilter()
                    {
                        Name = item.Key,
                        count = item.Value
                    });
                }
            }

【问题讨论】:

  • 我要摆脱的第一件事是ToDictionary - 它毫无意义,因为您从来没有将它用作字典。

标签: c# asp.net-mvc linq optimization


【解决方案1】:

首先要做的是摆脱那些 foreach 循环,因为它们与 LINQ 不协调,并抛弃字典,因为它毫无意义:

var lstHotelLocation = hotellocation.GroupBy(x => x)
                                    .Where(g => g.Key != "")
                                    .Select(g => new HotelLocation {
                                        Name = kv.Key,
                                        count = g.Count()
                                    })
                                    .ToList();

 var lstHotelType = hoteltype.GroupBy(x => x)
                             .Where(g => g.Key != "")
                             .Select(g => new HotelTypeFilter {
                                 Name = g.Key,
                                 count = g.Count()
                             })
                             .ToList();

如果你想进一步删除重复,你可以这样做:

static List<T> AssembleCounts<T>(IEnumerable<string> values, 
                                 Func<string, int, T> makeObject)
{
    return values.Where(x => !string.IsNullOrEmpty(x))
                 .GroupBy(x => x)
                 .Select(g => makeObject(g.Key, g.Count()))
                 .ToList();
}

var lstHotelLocation = AssembleCounts(hotellocation,
                                      (k, c) => new HotelLocation {
                                          Name = k, count = c
                                      });

var lstHotelType = AssembleCounts(hoteltype,
                                  (k, c) => new HotelTypeFilter {
                                       Name = k, count = c
                                  });

【讨论】:

  • 如果您摆脱了字典,count=g.Value 需要更改为 count=g.Count()(仅第二个示例)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 2019-03-17
  • 1970-01-01
  • 2014-06-10
相关资源
最近更新 更多