我在下面的行中收到错误.
temp.day1_veh_p = string.Join(Environment.NewLine, day1.Where(x => x.plannedTriips == 1).Select(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>().ToArray());
Run Code Online (Sandbox Code Playgroud)
错误消息正在发送
Unable to cast object of type '<>f__AnonymousType0`1[System.String]' to type 'System.String'.
Run Code Online (Sandbox Code Playgroud)
列表day1是类型
public class tripDetails
{
public string accountID { get; set; }
public string supplierName { get; set; }
public string supplierCode { get; set; }
public DateTime shiftFrom { get; set; }
public DateTime shiftTo { get; set; }
public int plannedTriips { get; set; }
public int actualTrips { get; set; }
public DateTime forDate { get; set; }
public string vehicleNumber { get; set; }
public string shiftCompletedOn { get; set; }
public class Comparer : IEqualityComparer<tripDetails>
{
public bool Equals(tripDetails x, tripDetails y)
{
return x.supplierCode == y.supplierCode;
}
public int GetHashCode(tripDetails obj)
{
return (obj.supplierCode).GetHashCode();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
问题是 new { value = ... }
更换:
Select(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()
Run Code Online (Sandbox Code Playgroud)
同
Select(x => x.vehicleNumber+":"+x.shiftCompletedOn)
Run Code Online (Sandbox Code Playgroud)
你排序了.你根本不需要它Cast<string>().
您的原始代码为每个记录创建一个匿名类型的新实例,该实例具有一个value使用所需字符串调用的成员; 第二个版本只是创建字符串.
在某种程度上,尝试这个没有什么不同:
class Foo
{
public string Bar {get;set;}
}
...
var foo = new Foo { Bar = "abc" };
string s = (string)foo; // doesn't compile
Run Code Online (Sandbox Code Playgroud)
是的,匿名类型不是字符串,所以替换它
.Select(x => new { value = x.vehicleNumber + ":" + x.shiftCompletedOn })
Run Code Online (Sandbox Code Playgroud)
同
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn)
Run Code Online (Sandbox Code Playgroud)
然后您可以使用查询(您不需要创建新数组)string.Join.
使用多行也很有帮助,它使您的代码更具可读性:
var vehicles = day1.Where(x => x.plannedTriips == 1)
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn);
string str = string.Join(Environment.NewLine, vehicles);
Run Code Online (Sandbox Code Playgroud)