之前学习数据库的时候总结过数据库中表和表之间的连接《数据库中多表的连接》,现在做的项目需要要调用其他系统WCF服务返回List集合,从自己系统再返回一部分集合,将这两种集合链接起来再将“连接的集合‘返回到界面。
通过查阅资料,有两种方法可以实现List集合之间的连接:一种是利用Linq语句,另外一种是利用lamda表达式,现在总结一下:
数据实体:
/// <summary> /// 考试实体 /// </summary> public class Exam { public string ExamId { get; set; } public string ExamName { get; set; } }
/// <summary> /// 考生实体 /// </summary> public class Examinee { public string ExamineeId { get; set; } public string ExamineeName { get; set; } public string ExamId { get; set; } }
向实体集合中添加数据:
//考试实体集合数据 List<Exam> examList=new List<Exam>() { new Exam(){ExamId ="ks001",ExamName = "数学考试"}, new Exam(){ExamId ="ks002",ExamName = "语文考试"}, new Exam(){ExamId ="ks003",ExamName = "英语考试"}, }; //考生实体集合数据 List<Examinee> examineeList = new List<Examinee>() { new Examinee(){ExamineeId = "xs1001",ExamineeName="小明",ExamId ="ks001",}, new Examinee(){ExamineeId = "xs1002",ExamineeName="小张",ExamId ="ks001",}, new Examinee(){ExamineeId = "xs1003",ExamineeName="小李",ExamId ="ks002",}, };
利用Linq语句
var joinList = from examEtity in examList join examineeEntity in examineeList on examEtity.ExamId equals examineeEntity.ExamId select new { 考试ID=examEtity.ExamId, 考试名称=examEtity.ExamName, 考生ID=examineeEntity.ExamineeId, 考生名称 = examineeEntity.ExamineeName }; dataGridView1.DataSource = joinList.ToList();
显示截图:
利用lamda表达式
var joinList = examList.Join(examineeList,examEntity=>examEntity.ExamId, examineeEntity => examineeEntity.ExamId, (examEntity,examineeEntity)=> new { 考试ID = examEntity.ExamId, 考试名称 = examEntity.ExamName, 考生ID = examineeEntity.ExamineeId, 考生名称 = examineeEntity.ExamineeName }); dataGridView1.DataSource = joinList.ToList();
显示截图:
总结:
这两种方式只是对于两个数据集合的内连接操作,还有左右连接、分组连接等等。那些还需要进一步的学习。
源码地址:http://download.csdn.net/detail/suneqing/8307283
时间: 2024-11-14 03:43:43