【问题标题】:Bind a list returned from a LINQ query to Gridview将从 LINQ 查询返回的列表绑定到 Gridview
【发布时间】:2013-04-27 11:50:02
【问题描述】:

我有一个类似这样的 linq 查询

var Query = from c in table
            where (some condition)
            select new {
            Name = c.Name,
            courses = // this returns a list,
            };

我如何将它绑定到gridview,以便结果是这样的

name1 course1
name1 course2
name1 course3
name2 course1
name2 course2

有什么想法吗?

【问题讨论】:

    标签: asp.net linq gridview


    【解决方案1】:

    下面试试

    gridview.DataSource = Query.ToList().Select(a => a.courses
                 .Select(c => new { Name = a.Name, Course = c }))
                 .SelectMany(p=>p).ToList();
    gridview.DataBind();
    

    如果你想从方法中返回这个列表,那么创建如下的类

    public class MyClass
    {
        public string Name { get; set; }
        public string Course { get; set; }
    }
    

    现在您可以将列表返回为

    public List<MyClass> MyMethod()
    {
        var Query = from c in table
                    where (some condition)
                    select new {
                    Name = c.Name,
                    courses = // this returns a list,
                    };
    
        return Query.ToList().Select(a => a.courses
                .Select(c => new MyClass{ Name = a.Name, Course = c }))
                .SelectMany(p=>p).ToList();
    }
    

    【讨论】:

    • 它不工作。在该列中显示 System.Collections.Generic.List`1[System.Int64]
    • 还有一件事我想问。此查询位于函数内部。函数的返回类型应该是什么?
    • 这正是我想要的。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2013-04-12
    相关资源
    最近更新 更多