将从LINQ查询返回的列表绑定到Gridview

时间:2013-05-03 06:13:27

标签: asp.net linq gridview

我有一个像这样的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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

尝试以下

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();
}