请有人帮我将此代码从C#转换为VB。这真让我疯狂。
private List<Customer> Customers
{
get
{
List<Customer> customers = HttpContext.Current.Session["Customers"] as List<Customer>;
// load the customers on first access
if (customers == null)
{
customers = new List<Customer>();
XDocument xDoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"App_Data\customers.xml"));
customers =
(
from c in xDoc.Descendants("customer")
orderby c.Attribute("CustomerID").Value
select new Customer
{
ID = c.Attribute("CustomerID").Value,
CompanyName = c.Attribute("CompanyName").Value,
ContactName = c.Attribute("ContactName").Value,
ContactTitle = c.Attribute("ContactTitle").Value,
Address = c.Attribute("Address").Value,
City = c.Attribute("City").Value,
State = c.Attribute("State").Value,
ZIPCode = c.Attribute("ZIPCode").Value,
Phone = c.Attribute("Phone").Value
}
).ToList();
// cache the list
HttpContext.Current.Session["Customers"] = customers;
}
return customers;
}
}
再次感谢你。
答案 0 :(得分:1)
我从automated conversion tool开始,然后稍微按下输出,以生成以下VB.NET代码:
公平警告:虽然这段代码对我来说很好,但我不是LINQ的专家。我强烈建议您自己测试代码,以确保它实际上能够满足您的需求!
Private ReadOnly Property Customers() As List(Of Customer)
Get
' Change the name of this variable, as VB is not case-sensitive
Dim customersList As List(Of Customer) = TryCast(HttpContext.Current.Session("Customers"), List(Of Customer))
' Load the customers on first access
If customersList Is Nothing Then
customersList = New List(Of Customer)()
Dim xDoc As XDocument = XDocument.Load(HttpContext.Current.Server.MapPath("App_Data\customers.xml"))
customersList = (From c In xDoc.Descendants("customer") _
Order By c.Attribute("CustomerID").Value _
Select New Customer() With { _
.ID = c.Attribute("CustomerID").Value, _
.CompanyName = c.Attribute("CompanyName").Value, _
.ContactName = c.Attribute("ContactName").Value, _
.ContactTitle = c.Attribute("ContactTitle").Value, _
.Address = c.Attribute("Address").Value, _
.City = c.Attribute("City").Value, _
.State = c.Attribute("State").Value, _
.ZIPCode = c.Attribute("ZIPCode").Value, _
.Phone = c.Attribute("Phone").Value _
}).ToList()
' Cache the list
HttpContext.Current.Session("Customers") = customersList
End If
Return customersList
End Get
End Property
答案 1 :(得分:0)
Cody的答案很好,但您可以利用VB.NET的xml功能以这种方式编写LINQ(我还没有测试过):
customersList = (From c In xDoc...<customer>
Order By c.@CustomerID
Select New Customer() With {
.ID = c.@CustomerID,
.CompanyName = c.@CompanyName,
.ContactName = c.@ContactName,
.ContactTitle = c.@ContactTitle,
.Address = c.@Address,
.City = c.@City,
.State = c.@State,
.ZIPCode = c.@ZIPCode,
.Phone = c.@Phone
}).ToList()
这只是在当前版本的VB中讨论后代和属性的一种更简单的方法。