询问者
linq里的非泛型集合的强制类型转换

问题
-
有如下的类,
class SunPlant
{
public string Name{get;set;}
public string Tag{get;set;}
}
然后在main方法里,
static void Main()
{
//定义一个非泛型集合
ArrayList plants = new ArrayList
{
new SunPlant{Name="a",Tag="red"},
new SunPlant{Name="b",Tag="red"},
new SunPlant{Name="c",Tag="green"},
}
//然后新建一个Linq查询
var query = from SunPlant p in plants where p.Tag =="red" select p;
}
想问下,这个query语句里的强制转换 SunPlant p是什么作用?
- 已编辑 imeya 2018年1月16日 9:24
全部回复
-
var query = select SunPlant p from plants where p.Tag =="red" select p; 这不是linq吧,这么写会报错的。而且要实现IEnumerable接口的才能使用linq,ArrayList集合用不了linq。
var plants = new List<SunPlant>
{
new SunPlant{Name="a",Tag="red"},
new SunPlant{Name="b",Tag="red"},
new SunPlant{Name="c",Tag="green"},
};
var query = from p in plants
where p.Tag == "red"
select p; -
Hi imeya,
你这样写的确是可以的,我这边测试也是没问题的,arraylist 也的确没有继承IEnumerable<T>。
问题在于你手动定义了这个变量。 这样非泛型的arraylist 也可以使用LINQ语句。
When using LINQ to query non-generic IEnumerable collections such as ArrayList, you must explicitly declare the type of the range variable to reflect the specific type of the objects in the collection.
详细的信息,看这个文档。
Best Regards,
Hart
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.
- 已建议为答案 Hart WangModerator 2018年1月19日 3:03