2014-09-19 121 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