我在下面的行中收到错误。
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());
错误消息
Unable to cast object of type '<>f__AnonymousType0`1[System.String]' to type 'System.String'.
列表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();
}
}
}
我到底做错了什么?
答案 0 :(得分:6)
问题是new { value = ... }
替换:
Select(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()
与
Select(x => x.vehicleNumber+":"+x.shiftCompletedOn)
你排序了。您根本不需要Cast<string>()
。
您的原始代码为每条记录创建一个匿名类型的新实例,该实例具有名为value
的成员,并带有所需的字符串;第二个版本只是创建字符串。
在某种程度上,尝试这个并没有什么不同:
class Foo
{
public string Bar {get;set;}
}
...
var foo = new Foo { Bar = "abc" };
string s = (string)foo; // doesn't compile
答案 1 :(得分:5)
是的,匿名类型不是字符串,因此请替换此
.Select(x => new { value = x.vehicleNumber + ":" + x.shiftCompletedOn })
与
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn)
然后您可以使用string.Join
的查询(您不需要创建新数组)。
使用多行也很有帮助,它使您的代码更具可读性:
var vehicles = day1.Where(x => x.plannedTriips == 1)
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn);
string str = string.Join(Environment.NewLine, vehicles);
答案 2 :(得分:3)
替换此
(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()
由此
(x => String.Format("{0}\:{1}", x.vehicleNumber, x.shiftCompletedOn))
当您执行new { ... }
时,您正在创建匿名类型的项目,然后(Cast<string()
)尝试显式转换为string
并且未定义此转换 - 您最终会遇到相应的异常