2011-02-07 10 views
3

다음 오브젝트를 고려하십시오. LINQ 쿼리 (그룹 BY)?

public class Address { public string city; public string state; public string country; } 

주소리스트가있는 경우 도시, 주 및 국가가 일치하는 카운트 목록을 얻으려면 LINQ를 어떻게 사용합니까?

그러면 내 결과는 다음과 같이 보일 수 있습니다.

  • "princeton" "nj" "usa"122
  • "austin" "tx" "usa"44
  • "la" "ca ""usa "1
  • "princton ""na ""uk "3
  • ....

고마워요!

답변

9

마크의 대답보다 한 걸음 더 나아갔습니다 (게시하기 전에 편집 한 것입니다!). LOL

var qry = from addr in addresses 
      group addr by new { addr.city, addr.state, addr.country } into grp 
      select new 
      { 
      city = grp.Key.city, 
      state = grp.Key.state, 
      country = grp.Key.country, 
      count = grp.Count(), 
      }; 
2
var qry = addresses.GroupBy(addr => new { addr.city, addr.state, addr.country}); 

다음 (예를 들어) 할 수는

foreach(var row in qry) { 
    Console.WriteLine("{0} {1} {2} \t {3}", 
       row.Key.city, row.Key.state, row.Key.country, row.Count()); 
} 

즉, 각 그룹의 .Key 복합 new { addr.city, addr.state, addr.country}이며, 각 그룹은 IEnumerable<Address>이다. 즉, 데이터베이스 쿼리는 예를 들어, 정면 그것을 전체 의도를 알려 주어야 참고 : 현명한 쿼리를 할 수있는 최상의 기회를

var qry = from addr in db.Addresses 
      group addr by new { addr.city, addr.state, addr.country} into grp 
      select new { 
       grp.Key.city, grp.Key.state, 
       grp.Key.country, Count = grp.Count() 
      }; 

있도록 (안 N + 1).

1

이 내가 (LINQPAD에서) 뭘하려하고 잘 (Enigmativity '응답과 유사) 작동 :

void Main() 
{ 

    List<Address> lst = new List<Address>(); 
    lst.Add(new Address{ city = "ny", state = "cy", country = "india"}); 
    lst.Add(new Address{ city = "ny", state = "cy", country = "india"}); 
    lst.Add(new Address{ city = "by", state = "cy", country = "india"}); 
    lst.Add(new Address{ city = "ny", state = "fr", country = "india"}); 
     var qry = from addr in lst 
     group addr by new { addr.city, addr.state, addr.country } into grp 
     select new 
     { 
      city = grp.Key.city, 
      state = grp.Key.state, 
      country = grp.Key.country, 
      count = grp.Count(), 
     }; 
     qry.Dump(); 
} 
public class Address { public string city; public string state; public string country; } 

출력 : LINQ에서 그룹화에 대한

 
ny cy india 2 

by cy india 1 

ny fr india 1