2014-09-19 87 views
0

我需要优化我的代码。我有一些重复的代码。但我想优化它。任何人都可以帮助我优化我的代码。我怎样才能使共同功能为此?避免Linq在C#中重复组

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

我会摆脱的第一件事是ToDictionary - 它毫无意义,因为您从未将它用作字典。 – Jamiec 2014-09-19 10:01:37

回答

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

'count = g.Value'需要改成'count = g.Count()'(仅限第二个例子)如果你已经删除了字典 – Jamiec 2014-09-19 10:07:36

+0

@Jamiec Yup,谢谢。 – JLRishe 2014-09-19 10:10:22