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")