【问题标题】:Get data using LINQ and show result in a gridview使用 LINQ 获取数据并在网格视图中显示结果
【发布时间】:2014-05-04 18:47:10
【问题描述】:

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

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 中的网格表中。请帮忙!!

【问题讨论】:

  • 嗨,谢谢大家的回复,也许我的问题一开始并不清楚,我只想获取字符串数组中的模块,例如 Firstname = "cesar"。在网格视图中,我只想要与该用户名相关的模块。类似于:var query = from Student student in arrList where student.FirstName == "Cesar" select Student.modules;

标签: c# asp.net linq gridview


【解决方案1】:

您在查询结束时缺少 ToList。

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

然后将其绑定到您的 gridview。

【讨论】:

    【解决方案2】:

    考虑改用List<Student>

    List<Student> list = new List<Student>();  
        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();
    

    【讨论】:

      【解决方案3】:

      您应该避免使用 ArrayList。请改用列表。

      List<Student> StudentList = new List<Student>(); /* ... */
      

      你的查询应该是这样的:

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

      然后绑定你的网格:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-06
        • 2015-01-13
        • 2016-07-08
        • 2017-01-01
        • 2011-08-16
        • 1970-01-01
        相关资源
        最近更新 更多