繁体   English   中英

从C#到VB.Net将Linq转换为XML查询。 你能发现我的错误吗?

[英]Converting Linq to XML query from C# to VB.Net. Can you spot my error?

我将下面的Linq查询从C#转换为VB.Net。 你能发现我的错误吗? 该查询联接了3个XML数据集。 提前致谢!

C#-这个很棒。

List<Course> courses =
  (from course in CourseXML.Descendants(ns + "row")
  join coursecategory in CourseCategoryXML.Descendants("Table") on (string)course.Attribute("code") equals (string)coursecategory.Element("DATA")
  join category in CategoryXML.Descendants("Table") on (string)coursecategory.Element("GRP") equals (string)category.Element("GRP")
  where (string)coursecategory.Element("RECTYPE") == "C"
  select new Course {
    CategoryCode = category.Element("GRP").Value,
      Code = course.Attribute("code").Value
  }).ToList<Course>();

VB-我没有得到任何结果,所以我怀疑我的选拔不当或加入不当。

Dim result = (From course In CourseXML.Descendants(ns + "row") _
Join coursecategory In CourseCategoryXML.Descendants("Table") On CType(course.Attribute("code"), String) Equals CType(coursecategory.Element("DATA"), String) _
Join category In CategoryXML.Descendants("Table") On CType(coursecategory.Element("GRP"), String) Equals CType(category.Element("GRP"), String) _
Where CType(coursecategory.Element("RECTYPE"), String) = "C" _
Select New Course() With _ 
{ _
  .CategoryCode = category.Element("GRP").Value, _
  .Code = course.Attribute("code").Value _
}).ToList()

我使用以下网站进行转换: http : //www.developerfusion.com/tools/convert/csharp-to-vb/

Dim courses As List(Of Course) = (From course In CourseXML.Descendants(ns & "row") _
    Join coursecategory In CourseCategoryXML.Descendants("Table") On DirectCast(course.Attribute("code"), String) = DirectCast(coursecategory.Element("DATA"), String) _
    Join category In CategoryXML.Descendants("Table") On DirectCast(coursecategory.Element("GRP"), String) = DirectCast(category.Element("GRP"), String) _
    Where DirectCast(coursecategory.Element("RECTYPE"), String) = "C" _
    Select New Course()).ToList(Of Course)()

主要区别是最后一次选择。

由于强制转换,您得到的结果有所不同。

coursecategory.Element(“ RECTYPE”)。Value返回的结果与
(string)coursecategory.Element(“ RECTYPE”)==“ C”(显然还有CType(coursecategory.Element(“ RECTYPE”),String)=“ C”)。

如果您的元素之一缺少子RECTYPE节点,则如果正确转换它,将不会有任何结果,就像在VB.NET中所做的那样。

在C#中,您没有转换(string)coursecategory.Element(“ RECTYPE”)==“ C”。 如果使用ToString()或.Value,则会得到正确的结果。

请改用coursecategory.Element(“ RECTYPE”)。Value,并完全避免进行强制转换。

您可以通过将您的选择更改为返回值来进行测试:

select new { 
Wrong = (string)coursecategory.Element("RECTYPE"),  // No exception ... incorrect result!
//Maybe = coursecategory.Element("RECTYPE").ToString() //throws NullReferenceException
//Right = (string)coursecategory.Element("RECTYPE").Value // throws NullReferenceException because of a missing element.
CategoryCode = category.Element("GRP").Value,      
Code = course.Attribute("code").Value

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM