如何将空值存储到字典c#
我发现,如果我在数据库中的值为null,当我将其存储到字典时,应用程序将崩溃,以下是我的代码:如何将空值存储到字典c#,c#,linq,dictionary,C#,Linq,Dictionary,我发现,如果我在数据库中的值为null,当我将其存储到字典时,应用程序将崩溃,以下是我的代码: private async Task<Dictionary<string, string>> GetProducts(long productId) { return await _dbContext.Products .Where(prod => prod.productId == productId) .Select(prod =&
private async Task<Dictionary<string, string>> GetProducts(long productId)
{
return await _dbContext.Products
.Where(prod => prod.productId == productId)
.Select(prod => new
{
prod.ProductStockReferenceId,
prod.ProductTitle
})
.ToDictionaryAsync(x => x.ProductStockReferenceId, x => x.ProductTitle);
}
私有异步任务GetProducts(长productId)
{
return wait_dbContext.Products
.Where(prod=>prod.productId==productId)
.选择(prod=>new
{
prod.ProductStockReferenceId,
产品名称
})
.ToDictionaryAsync(x=>x.ProductStockReferenceId,x=>x.ProductTitle);
}
我已经意识到,如果数据库中的ProductStockReferenceId
为空,应用程序将崩溃,为什么会崩溃?我该怎么做才能防止这种情况发生
谢谢
干杯取决于您是否也要检索具有空ProductStockReferenceId的项目,您有两个选项
筛选出空值的记录:
return await _dbContext.Products
.Where(prod => prod.productId == productId && prod.ProductStockReferenceId != null)
.Select(prod => new
{
prod.ProductStockReferenceId,
prod.ProductTitle
})
.ToDictionaryAsync(x => x.ProductStockReferenceId, x => x.ProductTitle);
或者,您可以创建自定义(必须唯一)密钥并将有问题的项存储在其中:
var nullIndex = 0;
return await _dbContext.Products
.Where(prod => prod.productId == productId && prod.ProductStockReferenceId != null)
.Select(prod => new
{
prod.ProductStockReferenceId,
prod.ProductTitle
})
.ToDictionaryAsync(x => x.ProductStockReferenceId ?? $"null:{nullIndex++}", x => x.ProductTitle);
但请确保创建的自定义键不会出现在ProductStockReferenceId中,这样DbKeys和CustomKeys就不会重叠。其中(prod=>prod.productId==productId&&prod.ProductStockReferenceId!=null)?@John这意味着它将跳过ProductStockReferenceId为null的行?是的。没错。
null
不能用作字典中的键,因为您需要该键的哈希代码。而且密钥必须是唯一的。所以你可以用一些神奇的值来替换null
,但是如果你有多行,其中键是null
@RenéVogt,它仍然会崩溃。谢谢你的信息,先生!解决这个问题的变通方法是什么?你有什么建议?是否可以将这样的值添加到查找
,我的意思是查找是否支持“null”?