2011-08-09 3 views
0

내가 내 공급 업체 및 그들의 제품 수를 선택하려면 다음을 수행하고있어 값 :Linq에 가입, 그룹, 수> 더 선택 LINQ와

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new { 
    SupplierName = result.Key, 
    ProductCount = result.Count() 
} 

이 잘 작동하지만, 내가 더 몇 가지를 선택합니다 내 공급 업체 테이블 공급 업체 ID 및 SupplierAddress, 등으로부터 속성 :

....  
select new { 
    SupplierName = result.Key, 
    ProductCount = result.Count(), 
    SupplierId = .., 
    SupplierAddress = .., 
    } 

사람이 작업을 수행하는 방법을 알고 있나요

?

도와 주셔서 감사합니다.

+0

올바른 길을 가고 있습니다. 두 가지를 확인하십시오. 출력 클래스에 SupplierId 및 SupplierAddress를 저장할 필드가 있습니까? 코드의 일부만 붙여 넣기 만하면 LINQ를 포함하여 전체 행을 얻을 수 있습니까? – EtherDragon

답변

3

CompanyName이 같은 그룹 인 Supplier은 모두 IdAddress이 되겠습니까?

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by new { s.CompanyName, s.Id, s.Address } 
into result 
select new { 
    ProductCount = result.Count(), 
    SupplierName = result.Key.CompanyName, 
    SupplierId = result.Key.Id, 
    SuppliedAddress = result.Key.Address 
} 
+3

'result.FirstOrDefault() .Id'와'result.FirstOrDefault() .Address '에 암시 적으로 널 예외의 가능성이있다. – spender

+1

나는 splender와 동의합니다. 'null '을 체크하지 않고 값을 사용하려고한다면,'OrDefault' 버전을 사용할 필요가 없습니다. – svick

+0

@svick : 당신은 절대적으로 옳습니다. 어떤 이유로 LINQ에'First()'메소드가 없다고 상상해보십시오. 여기에 정말 늦었습니다. 잠을 좀 자야 할 것 같습니다. –

1

편집 내가 틀리지 않는

음 ...이 될 수 있습니다 : 당신이 그들 모두 어쩌면 대신 Id별로 그룹화, 또는 경우

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new { 
    SupplierName = result.Key, 
    ProductCount = result.Count(), 
    SupplierId = result.First().Id, 
    SuppliedAddress = result.First().Address 
} 

이 더 자연적인 것 상당히 깔끔하게 수행 :

context 
    .Products 
    .GroupBy(p=>p.Supplier) 
    .Select(result=>new { 
     SupplierName = result.Key, 
     ProductCount = result.Count(), 
     SupplierId = result.Key.Id, 
     SupplierAddress = result.Key.Address, 
    } 

는 FK의 RELATIO에서 상자 밖으로 나와 조인 DB에 nships가 있으므로 Product에는 이미 Supplier이 있습니다. 자신의 코드 (...equals p.Supplier)로이 설정을 발견 한 다음 그 의미를 이해하지 못했습니다. 이해 구문에서 메소드 체인으로 변경하는 것에 대해 사과드립니다. 그들은 내게 더 자연스럽게 온다.

Linq2Sql (Linq2Objects에 대해 정확할 수 있음)에 대한 보충 설명 (L2E를 보증 할 수는 없지만 대부분 동일하다고 상상해보십시오), FK에 의해 생성 된 속성별로 그룹화하면 결과로 생성 된 SQL은 전체 엔티티가 아니라 키 값으로 GROUP BY됩니다.

+1

이 기능이 작동하려면'Suppliers'가'IEquatable'을 구현해야합니다. –

+0

@ Dan, 귀하의 의견을 해결하기 위해 제 답변을 확장했습니다. – spender

+0

당신은 완전히 옳습니다, 나는 LINQ to SQL을 간과했습니다. –