LINQ To DataSet:联合查询

Student[] students = { new Student { Id = 1, Name = "Joe Rattz" }, new Student { Id = 7, Name = "Anthony Adams" }, new Student { Id = 13, Name = "Stacy Sinclair" }, new Student { Id = 72, Name = "Dignan Stephens" } }; StudentClass[] classDesignations = { new StudentClass { Id = 1, Class = "Sophmore" }, new StudentClass { Id = 7, Class = "Freshman" }, new StudentClass { Id = 13, Class = "Graduate" }, new StudentClass { Id = 72, Class = "Senior" } }; DataTable dt1 = GetDataTable(students); IEnumerable<DataRow> seq1 = dt1.AsEnumerable(); DataTable dt2 = GetDataTable2(classDesignations); IEnumerable<DataRow> seq2 = dt2.AsEnumerable(); string anthonysClass = (from s in seq1 where s.Field<string>("Name") == " from c in seq2 where c["Id"] == s["Id"] select (string)c["Class"]). SingleOrDefault<string>(); Console.WriteLine("Anthony's Class is: {0}", anthonysClass != null ? anthonysClass : "null");

输出

Anthony's Class is: null

这是为什么呢?因为这里发生的了装箱操作,

This is because of the boxing of the Id field when it is retrieved using the

DataRow indexer

在用DataRow索引器对Id字段进行检索的时候,该字段发生了装箱操作

导致join没有成功 "where c["Id"] == s["Id"]"

我们要做的就是给它拆箱,改为

where (int)c["Id"] == (int)s["Id"]

输出

Anthony's Class is: Freshman

上面人为的拆箱并不是很好的做法,所幸的是LiNQ为我们提供了泛型支持,看下面

Student[] students = { new Student { Id = 1, Name = "Joe Rattz" }, new Student { Id = 7, Name = "Anthony Adams" }, new Student { Id = 13, Name = "Stacy Sinclair" }, new Student { Id = 72, Name = "Dignan Stephens" } }; StudentClass[] classDesignations = { new StudentClass { Id = 1, Class = "Sophmore" }, new StudentClass { Id = 7, Class = "Freshman" }, new StudentClass { Id = 13, Class = "Graduate" }, new StudentClass { Id = 72, Class = "Senior" } }; DataTable dt1 = GetDataTable(students); IEnumerable<DataRow> seq1 = dt1.AsEnumerable(); DataTable dt2 = GetDataTable2(classDesignations); IEnumerable<DataRow> seq2 = dt2.AsEnumerable(); string anthonysClass = (from s in seq1 where s.Field<string>("Name") == "Anthony Adams" from c in seq2 where c.Field<int>("Id") == s.Field<int>("Id") select (string)c["Class"]). SingleOrDefault<string>(); Console.WriteLine("Anthony's Class is: {0}", anthonysClass != null ? anthonysClass : "null");

注意,已经改成使用泛型的形式

where c.Field<int>("Id") == s.Field<int>("Id")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值