我想使用一种优雅的方法来使用LINQ将几个列连接在一起,但是当任何列为NULL时使用+操作符或concat()将导致连接后的值为NULL。
是否有类似于concat()处理NULL不同的东西,或者我在考虑这个不正确的方式?
任何帮助都是感激的!
下面是我使用的代码:List<CustomObject> objects = (
from obj in ObjectTable
where obj.Id == Id
select new CustomObject()
{
EnteredBy = obj.EnteredBy,
EntryDate = obj.EntryDate,
WorknoteText =
obj.VchWorkNote1 +
obj.VchWorkNote2 +
obj.VchWorkNote3 +
obj.VchWorkNote4 +
obj.VchWorkNote5 +
obj.VchWorkNote6 +
obj.VchWorkNote7 +
obj.VchWorkNote8 +
obj.VchWorkNote9 +
obj.VchWorkNote10 +
obj.VchWorkNote11 +
obj.VchWorkNote12 +
obj.VchWorkNote13 +
obj.VchWorkNote14 +
obj.VchWorkNote15 +
obj.VchWorkNote16 +
obj.VchWorkNote17 +
obj.VchWorkNote18 +
obj.VchWorkNote19 +
obj.VchWorkNote20
}).ToList();
一种选择是使用空合并操作符:
List<CustomObject> objects = (from o in ObjectTable
where o.Id == Id
select new CustomObject(){
EnteredBy = o.EnteredBy,
EntryDate = o.EntryDate,
WorknoteText =
(o.VchWorkNote1 ?? "") +
(o.VchWorkNote2 ?? "") +
(o.VchWorkNote3 ?? "") +
(o.VchWorkNote4 ?? "") +
...
(o.VchWorkNote20 ?? "")
}).ToList();
希望生成的SQL将使用适当的翻译
你可以使用??操作符:
...
(object.VchWorkNote5 ?? "") +
(object.VchWorkNote6 ?? "") +
(object.VchWorkNote7 ?? "") +
...
如何(object.VchWorkNote1 ?? "") +
…
是否可以向数据库添加新列?比如"Keywords"或"FullText"
定义它有一个计算,这个计算基本上是"ISNULL(<Field1>, '') + ISNULL(<Field2>, '')"
等
确保将其标记为持久化,这样就不必每次都计算。
然后你只需要从你的表中拉下一个字段
可能有一个更干净的方法,但首先想到的是一个快速的空到零长度字符串转换:
List<CustomObject> objects = (from object in ObjectTable
where object.Id == Id
select new CustomObject(){
EnteredBy = object.EnteredBy,
EntryDate = object.EntryDate,
WorknoteText =
object.VchWorkNote1 ?? "" +
object.VchWorkNote2 ?? "" +
object.VchWorkNote3 ?? "" +
object.VchWorkNote4 ?? "" +
object.VchWorkNote5 ?? "" +
object.VchWorkNote6 ?? "" +
object.VchWorkNote7 ?? "" +
object.VchWorkNote8 ?? "" +
object.VchWorkNote9 ?? "" +
object.VchWorkNote10 ?? "" +
object.VchWorkNote11 ?? "" +
object.VchWorkNote12 ?? "" +
object.VchWorkNote13 ?? "" +
object.VchWorkNote14 ?? "" +
object.VchWorkNote15 ?? "" +
object.VchWorkNote16 ?? "" +
object.VchWorkNote17 ?? "" +
object.VchWorkNote18 ?? "" +
object.VchWorkNote19 ?? "" +
object.VchWorkNote20 ?? ""
}).ToList();