LinQ嵌套列表和嵌套选择

时间:2013-10-21 11:02:08

标签: c# linq

考虑这两个表:

 ClassID  Name
   1       C1
   2       C2

 ClassID  List<CourseSession>
   1            [Object that has value "A"], [Object that has value "B"]
   2            [Object that has value "B"], [Object that has value "C"]

当我在Linq中加入这两个表时,我得到:

ID Name List
1   C1  [A, B]
2   C2  [A, B]

我需要扩展它们:

ID Name List
1   C1  A
1   C1  B
2   C2  A
2   C2  B

Linq代码:

    var classes = from row in t.AsEnumerable() 
                               select new
                                  {
                                      ClassID = row.Field<Guid>("ClassID"),
                                      ClassName = row.Field<string>("Name"),
                                  };

    var classCourses = from row in classes.AsEnumerable()
                                   select new 
                                   {
                                       ID = row.ID,
                                       CourseSessionList = GetAllCoursesByID(row.ID).AsEnumerable()
                                   };

    //Attempt to join
    var expandedClassCourse = from classRow in classes 
                                   join ccRow in classCourses 
                                   on classRow.ID equals ccRow.ID
                                    into filteredExpandedClasses
                                   select filteredExpandedClasses;

我不确定如何实现这一目标。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

类似的东西(不确定你的模型是什么样的):

context.CouseSessions.Where(cs => /* condition goes here */)
    .Select(cs =>
        new
        {
            Name = cs.Name,
            Class = cs.Class.Name
        });

context.Classes.Where(c => /* condition goes here */)
    .SelectMany(c => c.Courses)
    .Select(cs =>
        new
        {
            Name = cs.Name,
            Class = cs.Class.Name
        });

答案 1 :(得分:1)

我根据假设创建了两个模型。我希望这会有所帮助。

class Info
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<string> List { get; set; }
    }

    class MyClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string s { get; set; }
    }

    static void Main(string[] args)
    {
        var infos = new List<Info> { new Info { Id = 1, Name = "c1", List = new List<string> { "A", "B" } }, new Info { Id = 2, Name = "c2", List = new List<string> { "A", "B" } } };
        var myClasses = new List<MyClass>();
        foreach (var info in infos)
        {
            myClasses.AddRange(info.List.Select(a => new MyClass { Id = info.Id, Name = info.Name, s = a }));
        }
    }

答案 2 :(得分:0)

(from c in classList
join s in sessionList on c.ClassID equals s.ClassID
select new
{
    ID = c.ClassID,
    Name = c.Name,
    SessionList = s.SessionList
})
.SelectMany(e => e.SessionList.Select(s => new
{
    ID = e.ClassID,
    Name = e.Name,
    Session = s
}))