LINQ:将多个int属性连接到一个字符串中
我有一个对象,其中有两个不同的整数属性,我试图在Linq to Entities中获得一个新对象,将同一对象中的两个整数属性组合为串联字符串,如下所示LINQ:将多个int属性连接到一个字符串中,linq,string,casting,concatenation,Linq,String,Casting,Concatenation,我有一个对象,其中有两个不同的整数属性,我试图在Linq to Entities中获得一个新对象,将同一对象中的两个整数属性组合为串联字符串,如下所示 List<DateRange> collection = (from d in context.dates select new DateRange { DateString = from s in context.Seasons where s.SeasonID = d.DateID select string
List<DateRange> collection = (from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select string.Format("{0} - {1}", s.StartYear, s.EndYear) }
).ToList<DateRange>();
不会编译年份的字符串连接。如果对象中的每个对象都是包含Number1和Number2字段或属性的类或结构,这将在LINQ to对象中起作用:
var results = from o in objects
select string.Format("{0} - {1}", o.Number1, o.Number2);
但是,您的原始代码也应该可以工作……如果您真的想要您所编写的内容,那么您的原始代码也可以工作。然而,如果你真的想从
var objects = new MyObject[]{
new MyObject {Int1 = 1, Int2 = 2},
new MyObject {Int1 = 3, Int2 = 4}};
比如你可以写1-2-3-4
var strings = objects.Select(o = > string.Format("{0} - {1}", o.Int1, o.Int2).ToArray();
var output = string.Join(" - ", strings);
假设您是通过LINQ to SQL/Entities连接到数据库,那么String.Format调用可能会失败,与那些提供程序一样,select子句在数据库中执行。并不是所有的东西都能从C转换成SQL 要将数据库结果转换为所需的字符串,应执行以下操作:
var temp = (
from d in context.dates
from s in context.Seasons
where s.SeasonID == d.DateID
select new { s.StartYear, s.EndYear }
).ToList(); // Execute query against database now, before converting date parts to a string
var temp2 =
from t in temp
select new DateRange
{
DateString = t.StartYear + " - " + t.EndYear
};
List<DateRange> collection = temp2.ToList();
编辑:
我还有一个想法。最有可能的问题是String.Format调用。我不确定它是否有效,但是一个普通的简·康卡特怎么样:
List<DateRange> collection =
(from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select s.StartYear + " - " + s.EndYear
}
).ToList<DateRange>();
当LINQ语句转换为SQL以便在服务器上执行时,StringConvert方法将转换为正确的转换函数。您的代码应该可以正常工作。您是否收到错误?假设您使用的是LINQtoSQL或LINQtoEntities,安全吗?我注意到context.dates和context.seasures…我不确定context是什么,但如果它是数据库上下文…这意味着您没有LINQ的全部功能,因为这些提供程序涵盖了IQueryable接口的大部分(但不是全部)。这些都是很好的建议。我正在使用Linq来创建实体。我想我的情况比我描述的更复杂。基本上是这样的设置:List collection=from d in context.dates选择new DateRange{DateRange=from s in context.seasures其中s.seasureid=d.DateID选择string.Format{0}-{1},s.StartYear,s.EndYear}.ToList;字符串连接将不会在此处编译。我将尝试此操作并报告。是的,此操作有效。正如您所猜测的那样,ToList非常重要,它首先返回resultset,然后使用第二个对象在数据库外部对其进行操作。我希望我的头脑和你的一样有条理!哈嗯,我不确定它是否这么有条理;P在过去,我在使用EFV1.0的过程中经历了艰辛,遇到了几乎所有的问题。这是一个相当普遍的问题。如果您有选择的话,我强烈建议您尽快使用EV v4.0和.NET 4.0,因为它是一种比EF v1或L2S功能更强的ORM。它还支持更多的转换以及自定义db函数映射,因此类似String.Format或自定义类似实现的东西实际上可以工作。很酷,谢谢。我将研究升级。伙计,很难跟上!
using System.Data.Objects.SqlClient;
:
:
List<DateRange> collection = (from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select SqlFunctions.StringConvert((double)s.StartYear) + " - " +
SqlFunctions.StringConvert((double)s.EndYear)
}).ToList<DateRange>();