在阅读了许多关于 LINQ to XML 的文章和许多使用分组的试验之后,我现在已经格式化了以下 LINQ 查询:
Dim objList = (From i In xmlDoc.Descendants("payment_amnt")
Group CType(i.Value, Decimal)
By Key = i.Parent.Element("account_id").Value.ToString() Into g = Group
Select New With {.ItemName = Key, .Sum = g.Sum()}).ToList()
我想添加另一个组密钥(“payment_mnth”)但是当我这样做时:
By Key = i.Parent.Element("account_id").Value.ToString(), Key = i.Parent.Element("payment_mnth").Value.ToString() Into g = Group
我得到错误。
如何向此查询添加第二个组键?
提前致谢。
斯蒂芬
PS:在戴维斯反馈后,我将以下内容添加到 linqpad 并收到此错误:对象引用未设置为对象的实例。
Dim xmlDoc As XDocument = XDocument.Load("c:\\Backup\PAYMENT.xml")
Dim objList = (From i In xmlDoc.Descendants("payment_amnt")
Group CType(i.Value, Decimal)
By AccountId = i.Parent.Element("account_id").Value.ToString(), PaymentMonth = i.Parent.Element("payment_mnth").Value.ToString() Into g = Group
Select New With {AccountId, PaymentMonth, g.Sum()}).ToList()
objList.Dump()
似乎是“By”部分中的 AccountId 导致了错误。我的 XML 如下:
<?xml version="1.0" encoding="utf-8"?>
<PAYMENT xmlns="urn:lst-emp:emp">
<PAYMENT xmlns="">
<id>1</id>
<paymentdate>17/06/2013</paymentdate>
<payment_no>1</payment_no>
<payment_to_id>1</payment_to_id>
<PAYMENT_TO>PWA</PAYMENT_TO>
<payment_type_id>1</payment_type_id>
<PAYMENT_TYPE>Computer Services</PAYMENT_TYPE>
<payment_request>Stephen</payment_request>
<payment_amnt>100</payment_amnt>
<comment></comment>
<payment_checked>0</payment_checked>
<GST>9.09</GST>
<payment_month>Jun</payment_month>
<account_id_transfer />
<account_id>1</account_id>
</PAYMENT>
<PAYMENT xmlns="">
<id>2</id>
<paymentdate>17/06/2013</paymentdate>
<payment_no>2</payment_no>
<payment_to_id>1</payment_to_id>
<PAYMENT_TO>PWA</PAYMENT_TO>
<payment_type_id>1</payment_type_id>
<PAYMENT_TYPE>Computer Services</PAYMENT_TYPE>
<payment_request>Stephens</payment_request>
<payment_amnt>1000</payment_amnt>
<comment></comment>
<payment_checked>0</payment_checked>
<GST>90.91</GST>
<payment_month>Jun</payment_month>
<account_id_transfer />
<account_id>1</account_id>
</PAYMENT>
<PAYMENT xmlns="">
<id>3</id>
<paymentdate>17/06/2013</paymentdate>
<payment_no>3</payment_no>
<payment_to_id>1</payment_to_id>
<PAYMENT_TO>PWA</PAYMENT_TO>
<payment_type_id>1</payment_type_id>
<PAYMENT_TYPE>Computer Services</PAYMENT_TYPE>
<payment_request>Stephen</payment_request>
<payment_amnt>145</payment_amnt>
<comment></comment>
<payment_checked>0</payment_checked>
<GST>13.18</GST>
<payment_month>Jun</payment_month>
<account_id_transfer />
<account_id>1</account_id>
</PAYMENT>
</PAYMENT>