linq 执行一对多的左连接查询

问题:

学生表,班级表,我要班级下面学生

A表,字段:AID,CLASS
B表,字段 :BID,BNAME,AID
A表数据
1 班级1
2 班级2
B表数据
1 学生1 1
2 学生2 1 
3 学生3 2
4 学生4 2
我想得到
CLASS NAME
班级1 学生1,学生2
班级2 学生3,学生4
这样怎么联合?

namespace ConsoleApplication1
{
    public class A
    {
        public int AID { get; set; }
        public string Class { get; set; }
    }

    public class B
    {
        public int BID { get; set; }
        public string BName { get; set; }
        public int AID { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<A> A = new List<A>() 
            { 
                new A(){ AID = 1, Class="班级1" },
                new A(){ AID = 2, Class="班级2" },
            };

            List<B> B = new List<B>() 
            { 
                new B(){ BID = 1 , BName = "学生1", AID=1 },
                new B(){ BID = 2 , BName = "学生2", AID=2 },
                new B(){ BID = 3 , BName = "学生3", AID=1 },
                new B(){ BID = 4 , BName = "学生4", AID=2 },
            };

            var lastResult = from p in A
                             join q in B.GroupBy(x => x.AID).Select(x => new { Key = x.Key, Value = string.Join(",", B.Where(y => y.AID == x.Key).Select(y => y.BName)) })
                             on p.AID equals q.Key
                             select new
                             {
                                 CLASS = p.Class,
                                 Name = q.Value,
                             };

            foreach (var item in lastResult)
            {
                Console.WriteLine(item);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/yougmi/p/12273683.html