我已经能够让Linq使用XML了,但是我想看看是否有更有效的方法将元素应用于对象而不是在遍历xml后放入foreach语句?我知道你可以使用lamba表达式,但不知道如何将其应用于此或如果可能的话?
任何建议都非常感谢。
List<Order> myOrders = new List<Order>();
var orders = from order in xdoc.Descendants("Order")
select new{
OrderNumber = order.Element("OrderNumber").Value,
OrderDate = order.Element("OrderDate").Value,
OrderTotal = order.Element("OrderTotal").Value
};
foreach(var ord in orders)
{
myOrders.OrderNumber = ord.OrderNumber;
myOrders.OrderDate = ord.OrderDate;
myOrders.OrderTotal = ord.OrderTotal;
}
答案 0 :(得分:4)
只需选择Order
个实例:
var orders = from order in xdoc.Descendants("Order")
select new Order {
OrderNumber = order.Element("OrderNumber").Value,
OrderDate = order.Element("OrderDate").Value,
OrderTotal = order.Element("OrderTotal").Value
};
orders
的类型为IEnumerable<Order>
,但如果您需要列表:
List<Order> myOrders = orders.ToList();
答案 1 :(得分:1)
使用以下内容替换您发布的代码
List<Order> myOrders = (from order in xdoc.Descendants("Order")
select new Order {
OrderNumber = order.Element("OrderNumber").Value,
OrderDate = order.Element("OrderDate").Value,
OrderTotal = order.Element("OrderTotal").Value
}).ToList();
答案 2 :(得分:0)
List<Order> myOrders = new List<Order>();
var orders = xdoc.Descendants("Order").Select(x=> new Order{
OrderNumber = x.Element("OrderNumber").Value,
OrderDate = x.Element("OrderDate").Value,
OrderTotal = x.Element("OrderTotal").Value
});
myOrders.AddRange(orders) // or just orders.ToList();