相关文章推荐
高大的毛衣  ·  将 Entity ...·  1 月前    · 
逆袭的斑马  ·  python git clone - CSDN文库·  9 月前    · 
豪爽的牛肉面  ·  Android Recycleview ...·  1 年前    · 
心软的吐司  ·  sql ...·  1 年前    · 

如果使用 LINQ 来查询非泛型 IEnumerable 集合(例如 ArrayList ),必须显式声明范围变量的类型,以反映集合中对象的特定类型。 例如,如果有 Student 对象的 ArrayList ,那么 from 子句 应如下所示:

var query = from Student s in arrList  
//...

通过指定范围变量的类型,可将 ArrayList 中的每项强制转换为 Student

在查询表达式中使用显式类型范围变量等效于调用 Cast 方法。 如果无法执行指定的强制转换,Cast 将引发异常。 CastOfType 是两个标准查询运算符方法,可对非泛型 IEnumerable 类型执行操作。 有关详细信息,请参阅 LINQ 查询操作中的类型关系

下面的示例演示对 ArrayList 的简单查询。 请注意,本示例在代码调用 Add 方法时使用对象初始值设定项,但这不是必需的。

using System;  
using System.Collections;  
using System.Linq;  
namespace NonGenericLINQ  
    public class Student  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public int[] Scores { get; set; }  
    class Program  
        static void Main(string[] args)  
            ArrayList arrList = new ArrayList();  
            arrList.Add(  
                new Student  
                        FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 }  
            arrList.Add(  
                new Student  
                        FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 }  
            arrList.Add(  
                new Student  
                        FirstName = "Sven", LastName = "Mortensen", Scores = new int[] { 88, 94, 65, 91 }  
            arrList.Add(  
                new Student  
                        FirstName = "Cesar", LastName = "Garcia", Scores = new int[] { 97, 89, 85, 82 }  
            var query = from Student student in arrList  
                        where student.Scores[0] > 95  
                        select student;  
            foreach (Student s in query)  
                Console.WriteLine(s.LastName + ": " + s.Scores[0]);  
            // Keep the console window open in debug mode.  
            Console.WriteLine("Press any key to exit.");  
            Console.ReadKey();  
/* Output:
    Omelchenko: 98  
    Garcia: 97  
  • LINQ to Objects (C#)
  •