# 将一条可音机的列与Where子句总结[英] Sum a IQueryable Column with where clause ### 问题描述

{''cast to value type'system.decimal'失败，因为 物质价值为无效.结果类型的通用参数要么 或查询必须使用无效类型."}

```var excessCount = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Count()  : 0;
```

```var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Sum(x => x.Value) : 0;
```

## 推荐答案

```var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost
.Where(x => x.Value > 150000)
.Sum(x => (decimal?) x.Value) : 0;
```

### 问题描述

I have 2 queries. One to find where Value column is greater than 150,000 and i need the count of entries. The second one is the sum of that rather than count. The Count works perfectly but the sum crashes and provides this error

{"The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}

Working code:

```var excessCount = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Count()  : 0;
```

Crashing Code:

```var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Sum(x => x.Value) : 0;
```

## 推荐答案

You can solve the issue by explicitly casting to decimal? in Sum like:

```var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost
.Where(x => x.Value > 150000)
.Sum(x => (decimal?) x.Value) : 0;
```

The issue is due to generated SQL from LINQ expression, and at C# end it will try to return decimal which can't accommodate a null value, hence the error.