无法投射物体

时间:2009-09-16 08:53:02

标签: linq

我是LINQ的新手,我试图运行以下代码并且我得到InvalidCastException错误:“无法将'd__3a`1 [debug.Product]'类型的对象转换为'debug.Product'' - 什么是错?

代码(VB - 使用VS2008)

    Private Sub btnLinq_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLinq.Click
        Dim Products As New List(Of Product)

        Dim p1 As New Product
        p1._ID = "1"
        p1._Name = "Product A"
        Products.Add(p1)

        Dim p2 As New Product
        p2._ID = "2"
        p2._Name = "Product B"
        Products.Add(p2)

        Dim p3 As New Product
        p3._ID = "3"
        p3._Name = "Product C"
        Products.Add(p3)

        Dim prod As Product = From p In Products Where p._ID = "1" Select p Take 1
        MsgBox(prod._ID)

    End Sub
End Class

Public Class Product
    Public _ID As String
    Public _Name As String
End Class

2 个答案:

答案 0 :(得分:11)

返回IEnumerable<Product>(在您的情况下),而不是产品。 (通过输出result.GetType())来检查它: (请注意,我的示例代码在C#中)

        List<Product> products = new List<Product> ();

        products.Add (new Product ()
        {
            Id = 1,
            Name = "Prod1"
        });

        products.Add (new Product ()
        {
            Id = 2,
            Name = "Prod2"
        });


        var result = ( from p in products
                       where p.Id == 1
                       select p ).Take (1);

        Console.WriteLine (result.GetType ());

        Console.ReadLine ();

就我而言,上面的代码输出:

System.Linq.Enumerable+<TakeIterator>d__3a`1[LinqTest.Product]

在您的情况下,您可以尝试使用First或FirstOrDefault而不是使用Take 1。

所以,试试这个:

        var result = ( from p in products
                       where p.Id == 1
                       select p ).FirstOrDefault ();

        Console.WriteLine (result.GetType ());
        Console.WriteLine (result.Name);

答案 1 :(得分:1)

Take方法(Enumerable.Take)不返回元素,而是返回另一个序列(IEnumerable<Product>)。 Take(n)只需使用 n 元素的最大创建一个新序列。

要从序列中获取第一个元素,请使用以下方法之一:

  • FirstOrDefault() - 如果序列为空,则返回null
  • First() - 如果序列为空则抛出InvalidOperationException