[C#] 소스 컬렉션이 비어있는 동안 LINQ Sum ()이 0을 반환하도록하는 방법

기본적으로 다음 쿼리를 수행 할 때 일치하는 리드가 없으면 다음 쿼리에서 예외가 발생합니다. 이 경우 예외가 발생하는 대신 합계를 0으로 설정하는 것이 좋습니다. 이것이 쿼리 자체에서 가능 query.Any()할까요? 쿼리를 저장하고 확인하는 것이 아니라 의미 합니까?

double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                && l.Date.Month == date.Month
                && l.Date.Year == date.Year
                && l.Property.Type == ProtectedPropertyType.Password
                && l.Property.PropertyId == PropertyId).Sum(l => l.Amount);



답변

다음과 같이 쿼리를 변경하십시오.

db.Leads.Where(l => l.Date.Day == date.Day
            && l.Date.Month == date.Month
            && l.Date.Year == date.Year
            && l.Property.Type == ProtectedPropertyType.Password
            && l.Property.PropertyId == PropertyId)
         .Select(l => l.Amount)
         .DefaultIfEmpty(0)
         .Sum();

이런 식으로 쿼리는 Amount필드 만 선택합니다 . 컬렉션이 비어 있으면 값이 1 인 요소를 반환 한 0다음 합계가 적용됩니다.


답변

다른 핵을 사용하는 것을 선호합니다.

double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                                      && l.Date.Month == date.Month
                                      && l.Date.Year == date.Year
                                      && l.Property.Type == ProtectedPropertyType.Password
                                      && l.Property.PropertyId == PropertyId)
                          .Sum(l => (double?) l.Amount) ?? 0;


답변

대신 시도해보십시오. 더 짧습니다.

db.Leads.Where(..).Aggregate(0, (i, lead) => i + lead.Amount);


답변

그것은 나를 위해 이겼다 :

int Total = 0;
Total = (int)Db.Logins.Where(L => L.id == item.MyId).Sum(L => (int?)L.NumberOfLogins ?? 0);

내 LOGIN 테이블의 NUMBEROFLOGINS 필드에서 일부 값은 NULL이고 다른 값은 INT 번호입니다. 한 회사의 모든 사용자 (각 ID)의 총 NUMBEROFLOGINS를 합산합니다.


답변

시험:

이중 수입 = db.Leads.Where (l => l.ShouldBeIncluded) .Sum (l =>
(double?) l.Amount) ?? 0 ;

SELECT SUM ([Amount]) ” 쿼리 는 빈 목록에 대해 NULL을 반환합니다. 그러나 LINQ를 사용하는 경우 ” Sum (l => l.Amount) “는 double을 반환하고 ” ?? “연산자를 사용하여 빈 컬렉션에 0을 설정할 수 없습니다 .

이 상황을 피하려면 LINQ가 ” double? “을 예상해야합니다 . ” (double?) l.Amount ” 를 캐스팅하면됩니다 .

SQL에 대한 쿼리에는 영향을 미치지 않지만 LINQ는 빈 컬렉션에서 작동합니다.


답변

db.Leads.Where(l => l.Date.Day == date.Day
        && l.Date.Month == date.Month
        && l.Date.Year == date.Year
        && l.Property.Type == ProtectedPropertyType.Password
        && l.Property.PropertyId == PropertyId)
     .Select(l => l.Amount)
     .ToList()
     .Sum();


답변