Linq 无法强制转换对象

Linq 无法强制转换对象,linq,Linq,我是LINQ新手,我尝试运行以下代码,但出现了InvalidCastException错误:“无法将类型为'd_u3a`1[debug.Product]'的对象强制转换为类型为'debug.Product'-怎么了 代码(VB-使用VS2008) Take返回一个IEnumerable(在您的情况下),而不是一个产品。 (通过输出result.GetType()进行检查): (请注意,我的示例代码是C#) Take方法(Enumerable.Take)不返回元素,而是返回另一个序列(IEnume

我是LINQ新手,我尝试运行以下代码,但出现了InvalidCastException错误:“无法将类型为'd_u3a`1[debug.Product]'的对象强制转换为类型为'debug.Product'-怎么了

代码(VB-使用VS2008)


Take返回一个
IEnumerable
(在您的情况下),而不是一个产品。 (通过输出result.GetType()进行检查): (请注意,我的示例代码是C#)


Take
方法(
Enumerable.Take
)不返回元素,而是返回另一个序列(
IEnumerable
Take(n)
只创建一个最多包含n个元素的新序列

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

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

尝试使用temp作为var,然后查看tem的类型。谢谢。。。您帮了大忙。如果您不想只使用第一项,您可以使用
.Take(10).ToList()
来获取通用列表,而不是可枚举列表。
    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
        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]
        var result = ( from p in products
                       where p.Id == 1
                       select p ).FirstOrDefault ();

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