2 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
Run Code Online (Sandbox Code Playgroud)
Fre*_*els 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 ();
Run Code Online (Sandbox Code Playgroud)
就我而言,上面的代码输出:
System.Linq.Enumerable+<TakeIterator>d__3a`1[LinqTest.Product]
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以尝试使用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);
Run Code Online (Sandbox Code Playgroud)