排名
7
文章
192
粉丝
15
评论
16
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

前言
SelectMarry实现的原理其实就是把一对多,或者集合解析成一对一
内部核心原理就是通过两个循环解析
解析方法
- //学生表(Scroe字段是一对多字段,包含空数据)
- List<GroupJoinClass> database = oaentities.Userchild.GroupJoin(oaentities.UserScroe, a => a.sid, b => b.ScroeUser, (a, b) => new GroupJoinClass
- {
- sid = a.sid,
- Username = a.Username,
- Fathername = a.Fid,
- scroe = b
- }).ToList();
-
-
- //定义集合接收
- List<OneByOneClass> rar = new List<OneByOneClass>();
- //循环遍历学生表
- foreach (GroupJoinClass item in database)
- {
- //再循环遍历一对多的字段使其变成一对一的对象
- foreach (UserScroe item2 in item.scroe)
- {
- //实例化空对象接收数据
- OneByOneClass onebyone = new OneByOneClass();
- //属性赋值
- onebyone.sid = item.sid;
- onebyone.username = item.Username;
- //为空验证(为空就跳过)
- if (item.scroe != null)
- {
- onebyone.Scroename = item2.ScroeName;
- onebyone.Scroenumber = item2.ScroeNum;
- }
- //将数据添加
- rar.Add(onebyone);
- }
-
- }
OneByOneClass对象部分
- public partial class OneByOneClass
- {
- public int sid { get; set; }
- public string username { get; set; }
- public string Scroename { get; set; }
- public string Scroenumber { get; set; }
- }
自定义扩展方法
- //list的父类 给泛型添加约束才能new出来
- public static IEnumerable<TResult> MySelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) where TCollection:new() where TResult:new()
- {
- //定义泛型集合接收
- List<TResult> rar = new List<TResult>();
- //循环主表(用户传输的第一个参数)
- foreach (TSource item in source)
- {
- //循环用户给出条件的字段(需要解析的字段)(一对多的部分)
- foreach (TCollection newitem in collectionSelector(item))
- {
- //null验证(定义一个空的对象,因为是分数可能为空,所以空数据点不出来,用一个空对象代替就可以避免报错)
- TCollection t2 = new TCollection();
- //定义一个空的泛型(装用户赋的值)
- TResult Userjoin = new TResult();
- //null验证(有数据传数据,为空传空对象)
- if (newitem == null)
- {
- Userjoin = resultSelector(item, t2);
- }
- else
- {
- Userjoin = resultSelector(item, newitem);
- }
- //将用户输入的数据添加进List
- rar.Add(Userjoin);
- }
- }
- return rar;
- }
通过学生表点出扩展方法(与系统自带方法基本一致)
-
- var database = oaentities.Userchild.GroupJoin(oaentities.Userfather, a => a.Fid, b => b.Cid, (user, parent) => new
- {
- user = user,
- Father = parent
- }).MySelectMany(a => a.Father.DefaultIfEmpty(), (last, parent) => new LeftJoinDatabeseController {
- sid = last.user.sid,
- Username = last.user.Username,
- Fathername = parent.Fathername
- });
-
- //现在的database就是一个一对一的对象
评价