![](/img/trans.png)
[英]Converting c# to vb.net. What to do with comparison operators and Interfaces?
[英]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.