3

我在下面的行中遇到错误。

 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();
        }
    }
}

我到底做错了什么?

4

3 回答 3

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
于 2013-03-07T11:56:00.767 回答
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);
于 2013-03-07T11:55:07.427 回答
3

替换这个

(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()

这样

(x => String.Format("{0}\:{1}", x.vehicleNumber, x.shiftCompletedOn))

当您这样做时,new { ... }您正在创建匿名类型的项目,然后 ( Cast<string()) 尝试显式string转换为并且未定义此类转换 - youn 最终会出现适当的异常。

于 2013-03-07T11:55:39.753 回答