避免在C#中由Linq重复组

时间:2014-09-19 09:57:45

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

我需要优化我的代码。我有一些重复代码。但我想优化它。任何人都可以帮我优化我的代码。我怎样才能为此增加常用功能?

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

1 个答案:

答案 0 :(得分:5)

要做的第一件事是摆脱那些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
                                  });