在 linq 中使用三元运算符来模拟基于 CASE 的串联

本文关键字:模拟 CASE 运算符 三元 linq | 更新日期: 2023-09-27 18:31:48

我正在尝试构建一个查询,其中我必须根据第三个字段的值将 2 个特定字段连接在一起:

var query = (from ds in Datacenter.datastatus
                     where ds.visible == "y" 
                     select new 
                     { 
                         ds.Priority, 
                         ds.country.Country_Name, 
                         ds.DSFromDate,
                         ds.DSToDate,
                         receptiontype = ds.Datatype == "QH" ? Datacenter.reception_type.Where(x => x.Id_reception_type == ds.country.ReceptionType_IdQH).Select(x => x.Name) + " - " + ds.country.ReceptionCommentQH :
                         ds.Datatype != "QH" ? Datacenter.reception_type.Where(x => x.Id_reception_type == ds.country.ReceptionType_Id).Select(x => x.Name) + " - " + ds.country.ReceptionComment :
                         ""                       
                     }).ToList();

就我而言,我将有 2 种不同的串联,具体取决于"数据类型"字段值是否等于"QH"。

运行代码时,我遇到了一个我不太了解的异常:"DBArithmeticExpression agruments 必须具有数字通用类型"

我认为错误可能来自我进行字符串连接的方式,因此尝试了以下代码:

 receptiontype = ds.Datatype == "QH" ? String.Concat(Datacenter.reception_type.Where(x => x.Id_reception_type == ds.country.ReceptionType_IdQH).Select(x => x.Name), " - ", ds.country.ReceptionCommentQH) :
                         ds.Datatype != "QH" ?  String.Concat(Datacenter.reception_type.Where(x => x.Id_reception_type == ds.country.ReceptionType_Id).Select(x => x.Name), " - ", ds.country.ReceptionComment):
                         ""

但是由于我使用的是实体框架,所以我得到了经典的"LINQ to Entities无法识别方法'System.String Concat',因为它似乎无法将连接转换为SQL。

关于如何执行我的串联的任何提示?

在 linq 中使用三元运算符来模拟基于 CASE 的串联

问题是Datacenter.reception_type.Where(x => x.Id_reception_type == ds.country.ReceptionType_IdQH).Select(x => x.Name)是一个集合。为此,您正在尝试连接一个字符串,这确实是荒谬的,因此第一种方法失败了。

如果集合应该只有一个项目,请使用 .First().Single(),然后与+运算符连接。

如果集合应该有多个需要连接的项目......那我不知道。