我需要连接4个字段并使用|
分隔符显示为单个字段。我试过了string.Concat()
,但它没有用。还尝试使用string.Join()
但无法使用它。
var result = dbContext.MyEntity
.Where(me=> me.field1!= null && me.field2 != null)
.Select(me => new MyViewModelClass()
{
Field1 = me.field1,
Field2 = me.field2,
Field3 = me.field3,
Field4 = me.field4,
Field5 = me.field5,
Field6 = me.field6,
// I need to concatenate field3, field4, field 5, field 6 by "|" separator.
Field = string.Concat("|", me.field3, me.field4, me.field5, me.field6)
});
return result;
有什么建议吗?
谢谢,
答案 0 :(得分:3)
您需要在.ToList()
和Where
子句之间放置一个Select
,以便LINQ将使用LINQ-to-Objects提供程序(可以使用C#字符串方法)而不是LINQ-to-Entities提供程序(由于它正在尝试将其转换为SQL查询,因此无法提供)。
您的代码将是这样的:
var result = dbContext.MyEntity
.Where(me=> me.field1 != null && me.field2 != null)
.ToList()
.Select(me =>
new MyViewModelClass()
{
Field1 = me.field1,
Field2 = me.field2,
Field3 = me.field3,
Field4 = me.field4,
Field5 = me.field5,
Field6 = me.field6,
Field = string.Concat("|", me.field3, me.field4, me.field5, me.field6)
}
);
答案 1 :(得分:1)
<强>更新强> 请按照@ IronMan84的建议进行操作并应用.ToList()。此外,如果您想提高效率,可以使用string.format
Field = string.Format("{0}|{1}|{2}|{3}",me.field3,me.field4,me.field5,me.field6);
如果您使用的是c#6.0(.NET Framework&gt; = 4.6.1),则可以使用
Field = $("{me.field3}|{me.field4}|{me.field5}|{me.field6}");
答案 2 :(得分:0)
var result= dbContext.MyEntity.Where(me=> me.field1!= null && me.field2 != null).Select(me=>
new MyViewModelClass()
{
Field1= me.field1,
Field2= me.field2,
Field3= me.field3,
Field4= me.field4,
Field5= me.field5,
Field6= me.field6,
//I need to concatenate field3, field4, field 5, field 6 by "|" separator.
Field= string.Concat("|",me.field3).Concat("|")
.Concat(field4).Concat("|")
.Concat(field5).Concat("|")
.Concat(field6)
});
return result;