使用LINQ获取数据并在gridview中显示结果

如何使用C#和Asp.net中的Linq从下面的数组中获取学生firstName的所有模块。 这可能很容易做但却未能成功。 请帮忙。 谢谢。

ArrayList arrList = new ArrayList(); //new array list for students arrList.Add( new Student { FirstName = "Svetlana", LastName = "Omelchenko", Password = "hh", modules = new string[] { "001", "002", "003", "004" } }); arrList.Add( new Student { FirstName = "Claire", LastName = "O'Donnell", modules = new string[] { "001", "002", "003", "004" } }); arrList.Add( new Student { FirstName = "Sven", LastName = "Mortensen", modules = new string[] { "001", "002", "003", "004" } }); arrList.Add( new Student { FirstName = "Cesar", LastName = "Garcia", modules = new string[] { "HH", "KK", "LL", "OO" } }); var query = from Student student in arrList where student.FirstName == "Cesar" select query; GridView1.DataSource = query; GridView1.DataBind(); 

我想将结果放在Asp.net的网格表中。 请帮忙!!

您在查询结束时缺少ToList。

 yourGridView.DataSource = (from Student s in arrList where s.FirstName == "Cesar" select s).ToList(); 

然后将其绑定到gridview。

你应该避免使用ArrayLists。 改用List。

 List StudentList = new List(); /* ... */ 

你查询应该看起来像:

 var query = from student in StudentList where student.FirstName == "Cesar" select student; 

然后绑定你的网格:

  GridView1.DataSource = query.ToList(); GridView1.DataBind(); 

请考虑使用List

 List list = new List(); list.Add( // ... Just like in your OP }); 

然后得到结果:

 var result = from student in list where student.FirstName == "Cesar" select student; 

然后,您应该能够使用返回的IEnumerable上的ToList()将结果添加到数据源:

  gridView.DataSource = result.ToList();