2014-01-16 199 views
3

我做了一個C#LINQ查詢,按屬性分類(或分組),我幾乎可以肯定有一個更好的方法。我的項目充滿了這些疑問,所以我對如何以正確的方式實現這一目標非常感興趣。正確的方法來分類屬性

這是我的查詢什麼樣子:JSON輸出的

var g = _repository.GetEmployees(); 
var result = 
    g.GroupBy(x => x.City, (key, group) => group.First()) 
    .Select(x => new { 
     city = x.City, 
     employees = g 
      .Where(y=>y.EmployeeID == x.EmployeeID) 
      .Select(y=> new { 
       fullname = y.FirstName + " " + y.LastName, 
       title = y.Title 
      }) 
      .OrderBy(y=>y.fullname) 
    }) 
    .OrderBy(x => x.city); 

樣品:

[ 
    { 
     "city":"Barcelona", 
     "employees":[ 
      { 
       "fullname":"Foo Bar", 
       "title":"Help Desk Technician" 
      }, 
      { 
       "fullname":"Lorem Ipsum", 
       "title":"Information Technology Director" 
      } 
     ] 
    }, 
    { 
     "city":"London", 
     "employees":[ 
      { 
       "fullname":"Le Query", 
       "title":"Information Technology Manager" 
      }, 
      { 
       "fullname":"Please Help", 
       "title":"Management Information Systems Director" 
      } 
     ] 
    } 
] 

結果是好的。實現它的最好方法是什麼?

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

@JohnSaunders謝謝,對不起 –

回答

5

這聽起來像你只是想:

var result = g.GroupBy(x => x.City, (key, group) => new { 
          city = key, 
          employees = group.Select(emp => new { 
           fullname = emp.FirstName + " " + emp.LastName, 
           title = emp.Title 
          }) 
         }); 

換句話說,你只是在爲每個組,這是「匿名類型與城市的投影,併爲全市所有員工」。

+0

絕對完美!非常感謝。當然,我應該買一本你的書:) –