C# 如果 linq 查询中的值为空,如何分配空字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16490509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign empty string if the value is null in linq query?
提问by Meow
I have following LINQ query to get a set of data.
我有以下 LINQ 查询来获取一组数据。
var fields = from row in datarows
from field in row
from col in columnnames
where field.Key == col
select new { ColumnName = col, FieldValue = field.Value };
The problem is that my code that handle the fields after this query fails because field.Valueof some rows are returning null.
问题是我处理此查询后的字段的代码由于field.Value某些行返回而失败null。
My goal is to assign an empty string if nullis detected.
我的目标是在null检测到时分配一个空字符串。
Something like if field.Value == null, then field.Value = ""
就像是 if field.Value == null, then field.Value = ""
Is it possible to do so in linq query?
在 linq 查询中可以这样做吗?
采纳答案by Jon
回答by Justin Niessner
FieldValue = field.Value ?? String.Empty
回答by Claudio Redi
Use the null-coalescing operator
select new { ColumnName = col, FieldValue = field.Value ?? string.Empty };
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
这 ??运算符称为空合并运算符,用于为可空值类型或引用类型定义默认值。如果操作数不为空,则返回左侧操作数;否则返回正确的操作数。
回答by PSL
回答by Daniel M?ller
FieldValue = field.Value == null ? "" : field.Value
FieldValue = field.Value == null ?"" : 字段.值
回答by arunlalam
var fields = from row in datarows
from field in row
from col in columnnames
where field.Key == col
select new { ColumnName = col, FieldValue = field.Value == null ? string.Empty: field.Value};
回答by mfsumption
I also learned that if you are concatenating two fields in a linq field assignment and you are using the null-coalescing operator on only one of the fields, then you need to put parentheses around the field statement as such:
我还了解到,如果您在 linq 字段赋值中连接两个字段,并且仅在其中一个字段上使用空合并运算符,那么您需要在 field 语句周围加上括号,如下所示:
StreetAddr = customer.StreetAddr + ", " + (customer.Suite ?? "")
However, this code is not so great either because if the "Suite" field is null, then I still got that comma-space ", " hanging out after the "StreetAddr" field. Wish I knew a way to fix that?
但是,这段代码也不是很好,因为如果“Suite”字段为空,那么我仍然在“StreetAddr”字段之后得到逗号空格“,”。希望我知道解决这个问题的方法吗?

