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

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值