linq to xml Sum

I am just learning linq and am stopped by trying to get a sum of element 
values.

The xml is like this:

<LineItems>
    <lineItem>
        <Itemnum>123</Itemnum>
        <Quantity>6</Quantity>
    </lineItem>
    <lineItem>
        ...
    </lineItem>
</LineItems>

I use this Linq:

            Dim qty As IEnumerable(Of XElement) = From item In 
Order.Elements("LineItems").Descendants("lineItem") Select item.<Quantity>

but this does not work and I don't know the correct format: qty.Sum

Can someone suggest how to do this or a tutorial?

Rick

0
Rick2256 (24)
7/8/2008 2:38:06 PM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
851 Views

Similar Articles

[PageSpeed] 16

Rick wrote:
> I am just learning linq and am stopped by trying to get a sum of element 
> values.
> 
> The xml is like this:
> 
> <LineItems>
>    <lineItem>
>        <Itemnum>123</Itemnum>
>        <Quantity>6</Quantity>
>    </lineItem>
>    <lineItem>
>        ...
>    </lineItem>
> </LineItems>
> 
> I use this Linq:
> 
>            Dim qty As IEnumerable(Of XElement) = From item In 
> Order.Elements("LineItems").Descendants("lineItem") Select item.<Quantity>
> 
> but this does not work and I don't know the correct format: qty.Sum

Here is one example to do that:

         Dim order As XDocument = <?xml version="1.0"?>
                                  <LineItems>
                                      <lineItem>
                                          <Itemnum>123</Itemnum>
                                          <Quantity>6</Quantity>
                                      </lineItem>
                                      <lineItem>
                                          <Quantity>5</Quantity>
                                      </lineItem>
                                  </LineItems>
         Dim qty As IEnumerable(Of XElement) = From item In 
order.Elements("LineItems").Descendants("lineItem") Select 
item.<Quantity>(0)
         Console.WriteLine(qty.Sum(Function(q) CType(q, Decimal)))


And here is another using the LINQ query syntax:

         Dim order As XDocument = <?xml version="1.0"?>
                                  <LineItems>
                                      <lineItem>
                                          <Itemnum>123</Itemnum>
                                          <Quantity>6</Quantity>
                                      </lineItem>
                                      <lineItem>
                                          <Quantity>5</Quantity>
                                      </lineItem>
                                  </LineItems>
         Dim qty As IEnumerable(Of XElement) = From item In 
order.Elements("LineItems").Descendants("lineItem") Select 
item.<Quantity>(0)
         Console.WriteLine(Aggregate q In qty Into Sum(CType(q, Decimal)))


Note that the Select has item.<Quantity>(0), that is crucial.


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1778)
7/8/2008 4:08:48 PM
Thanks Martin, that was a big time saver!

Rick

"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:%23Hj%23rTR4IHA.1420@TK2MSFTNGP06.phx.gbl...
> Rick wrote:
>> I am just learning linq and am stopped by trying to get a sum of element 
>> values.
>>
>> The xml is like this:
>>
>> <LineItems>
>>    <lineItem>
>>        <Itemnum>123</Itemnum>
>>        <Quantity>6</Quantity>
>>    </lineItem>
>>    <lineItem>
>>        ...
>>    </lineItem>
>> </LineItems>
>>
>> I use this Linq:
>>
>>            Dim qty As IEnumerable(Of XElement) = From item In 
>> Order.Elements("LineItems").Descendants("lineItem") Select 
>> item.<Quantity>
>>
>> but this does not work and I don't know the correct format: qty.Sum
>
> Here is one example to do that:
>
>         Dim order As XDocument = <?xml version="1.0"?>
>                                  <LineItems>
>                                      <lineItem>
>                                          <Itemnum>123</Itemnum>
>                                          <Quantity>6</Quantity>
>                                      </lineItem>
>                                      <lineItem>
>                                          <Quantity>5</Quantity>
>                                      </lineItem>
>                                  </LineItems>
>         Dim qty As IEnumerable(Of XElement) = From item In 
> order.Elements("LineItems").Descendants("lineItem") Select 
> item.<Quantity>(0)
>         Console.WriteLine(qty.Sum(Function(q) CType(q, Decimal)))
>
>
> And here is another using the LINQ query syntax:
>
>         Dim order As XDocument = <?xml version="1.0"?>
>                                  <LineItems>
>                                      <lineItem>
>                                          <Itemnum>123</Itemnum>
>                                          <Quantity>6</Quantity>
>                                      </lineItem>
>                                      <lineItem>
>                                          <Quantity>5</Quantity>
>                                      </lineItem>
>                                  </LineItems>
>         Dim qty As IEnumerable(Of XElement) = From item In 
> order.Elements("LineItems").Descendants("lineItem") Select 
> item.<Quantity>(0)
>         Console.WriteLine(Aggregate q In qty Into Sum(CType(q, Decimal)))
>
>
> Note that the Select has item.<Quantity>(0), that is crucial.
>
>
> -- 
>
> Martin Honnen --- MVP XML
> http://JavaScript.FAQTs.com/ 

0
Rick2256 (24)
7/8/2008 4:52:56 PM
Reply:

Similar Artilces:

Working with XML Files in Dexterity
I have a lot of programming ahead of me (and behind me) working with XML, and I'm working exclusively with Dex (as I have been for 11 years). We need to do some some pretty serious and robust XML file exchanges for various types of transactions. There seems to be two ways to go about this in Dex: 1) going line-by-line looking at nodes with the "dataNode.childNodes.item..." functions, and maneuvering data types for EACH item in a table, For Example: dataNode = rootnodeDispatch.selectSingleNode("VehicleModel"); if not empty(dataNode) then NodeText = dataNode; dat...

summing text boxes
I have a subform that has a number of text boxes for different types of holiday and I have created a new text box that totals these text boxes. The problem I have come across is that the total isn't restricted to a single record. Absences in the next record gets added to the total (make sense?). What is the work around? Cheers!!!! scubadiver, Please describe each of the fields, sample values from those fields, the expected result, and the calculation you have to sum them. -- hth Al Campagna . Candia Computer Consulting . Candia, NH USA Microsoft Access MVP http://home.comcast.n...

Change the XML elements sequence
I export some database data to an XML file. How do I change the sequence of the elements (fields) appear in the XML document? For example, my XML output from TableA is: <TableA> <Field(0)> <Field(1)> <Field(2)> <Field(3)> </TableA> If I want to change the sequence of the fields to: <TableA> <Field(0)> <Field(3)> <Field(1)> <Field(2)> </TableA> Does anyone know what is the easiest way to do this without using "select" statement? (Because this example has been simplified for easier illustrat...

LINQ to XML - Performance
Hi, Can anyone tell me how the performance compares between working with xml documents in the normal way (i.e. with xpath and the System.Xml) and LINQ. Is it any quicker or slower? Are there are distinct benefits to the user (and not just advantages for the coder) to working with LINQ? The work i will be doing is creating an xml document out of segments from other xml documents, transforming the document (XSL) and then retrieving/amending/appending data to the document. Currentlly xml transformations in .net 2.0 are very slow and performance takes a real hit with complex transforms. ...

Generete an XML instance from its XSD
Hi Is there a way to generate in code an empty instance of an XML from it's XSD? I have a lot of schemas and I want at run time to create an empty instance for them (I then have to fill one or two fields). Shahar Shahar Ron wrote: > Is there a way to generate in code an empty instance of an XML from it's XSD? > I have a lot of schemas and I want at run time to create an empty instance > for them (I then have to fill one or two fields). Check out this article <URL:http://msdn2.microsoft.com/en-us/library/aa302296.aspx> which has code to create a sample documen...

Advanced filtering and sums
I have a large table with columns of data that I wish to consolidate similar lines of data using advanced filters. However, the last column is $$ amounts. When I initiate the filters to show unique records, the columns preceding the $$ filter correctly. However, in the amount column, only the first cell of $$ is captured. Is there a way to filter on unique records and have it sum the amount column? Use the Advanced Filter to produce unique records somewhere else (eg on a separate sheet). Then you can use SUMIF to produce sums for each unique record. Hope this helps. Pete On Sep 1...

XML Inheritance
I posted this message yesterday on a different group which may have been the wrong group, so I am not cross posting on purpose. Hi, I have a question regarding how the .Net framework interprets schema definitions based on existing types. I have (for the purposes of demonstration) a very simple types schema which contains some PersonName (T_PERSONNAME) and Address (T_ADDRESS) details as below. <?xml version="1.0" encoding="utf-16" ?> - <xs:schema xmlns=http://com.test.schemas.BaseTypes xmlns:b="http://schemas.microsoft.com/BizTalk/2003" ...

How to MoveFirst, MoveNext, MovePrevious, MoveLast in LinQ To XMl Please Help
I have the Next XML var xml = new XElement( "clients", new XElement("client", new XAttribute("id",1), new XElement( "name", "Luis"), new XElement( "country", "Portugal") ), new XElement("client", new XAttribute("id",2), n...

Linq or dictionary
Hi, I am pretty new to Linq and I am not quite sure when it is best to use it and when other methods might be preferable. For example, I need to create a list of Sample objects which I then access by the SampleName property of each sample. The way I have generally done this would be with a Dictionary<string, Sample>, but instead I can use a List<Sample> and access using linq. I don't know which would be preferable. Any thoughts? I have example code below. Thanks! Ethan With Dictionary Dictionary<string, Sample> samples = new Dictionary<strin...

Sum according to cell info
I want to sum three column of numbers according to a category number that lies in three columns, The category numbers are in columns B5 - B61 and then starting at N5 - N61 and then again starting at Z5 - Z24. The category numbers are 1 - 6. But may add categories later. I would like the sums to go into cells AH32 - AH37. -- Thank You in Advance Ed Davis I am sorry I forgot to mention where the data is I am looking for. F5 - F61 R5 - R61 AD5 - AD24 -- Thank You in Advance Ed Davis "Ed Davis" <ed@danverssoftware.com> wrote in message news:uumtXNdGKHA.3708@TK2MSFTNGP...

how to write some xml into huge xml file into speceific location???
Hello! Is anyone can help me to figure out how to write some xml into huge xml file into speceific location??? Say, i have a file about 139 Mb and i need to write some data (xml) into it, but in speceific location (specified by XPath for example). i have tryed used MSXML dom for it, but its eats memory like a twice bigger then my file. Is any way to do that without that hurt? thank you, Xenia. Xenia wrote: > Is anyone can help me to figure out how to write some xml into huge xml file > into speceific location??? > > Say, i have a file about 139 Mb and i need to write some d...

Automatically excluding "#VALUE!" from "SUM" function
I have a worksheet that column B multiplies the column A by 0.3825 in each cell. If I have to put a letter (such as n/a), not a number, in column a, corresponding cell in column B becomes "#VALUE!" and my total in column B is also distorted. Is there a formula that I can automatically exclude the non-numeric value from the "SUM" function? Thank you for your help. One way around this is: in B10 =IF(ISNUMBER(A10),(A10*0.3825),"") There are other methods using the error function but these can becom over complicated. Hope this helps Mik -------------------...

XML/DTD interpreted display...
Is there control in VB2005 (VS8.0) that can display & allow editing of mixed content XML as defined in specified DTD WYSIWYG style??? Thanks in Advance... -- Timothy Casey GPEMC! >> 11950 is the number@fieldcraft.com.au 2email Terms & conditions apply. See www.fieldcraft.biz/GPEMC Discover valid interoperable web menus, IE security, TSR Control, & the most advanced speed reading application @ www.fieldcraft.biz Number 11950 - GPEMC! Replace number with 11950 wrote: > Is there control in VB2005 (VS8.0) that can display & allow editing of mixed > cont...

Question about XML schema and blank element
Hey there, I'm running into an issue and wondered if any of you XML gurus know a solution. I'm currently using XML as a data transport mechanism between two applications and an XML schema for format validating purposes. Whenever I have an child element that is nested inside another element, the child element must not be empty or I get the following error message: "'Element' is an invalid node type." I've worked around this by adding a filler element as the first child element with junk as the inner text. The error only occurs if the FIRST child element is empt...

Summing 2 columns based on variables
This replicates through hundreds of rows. I need the total hours scheduled by day based on the 0 or 1s in the cloumns , and the # of variable hours in the z column. In the following, in cell S2, I need a formula to look at S5, if it's a zero, then 0, if it's a 1, then add whatever is in the z column ( in this case an 8), then to add up all the S column cells based on if there' a 1 in that column, then whatever the Z column shows. In this scenario, cell S1 would have 18, because 1's are in 7,8 &9 -SUM(Z7:Z9). And U2 would have 24, because 1's are in 5,6,&am...

Linq to BindingList
Hello. How can I send the result of a LINQ query to a BindingList? I say not to do this: <Customer> List lst = (from cust in select new dataContext.Customer Customer (cust)). ToList <Customer> (); foreach (Customer c in lst) lbindingListCust.Add (c); Any ideas? ...

XML Custom serialization
Hi all, I want to serialize a class in a customized way. But I don't want to implement the ISerializable interafce because I don't want to take care of every new field I insert to the class. What I need is a way to customize the serialization of a specific field in my class but leave the rest to the build-in serialization. Any guidance will be appreciated. Ro'ee <sfa.roy@gmail.com> wrote in message news:7243a1eb-3fa3-43e0-8339-d90f890e6716@b1g2000hsg.googlegroups.com... > Hi all, > > I want to serialize a class in a customized way. But I don't want to >...

Need help with query summing hours
Tring to get total worked hours and total maintenance hours summary. I have a table with the clock hours WorkID WorkDate WorkEmployeeID WorkHours And have a maintenace table MaintID MaintDate MaintEmployeeID MaintHours Needing help combining the information to get summary something like this.. Date - Employee - Clock Hours - Maintenance Hours 1/1/10 Joe Billy Bob 8 6 1/1/10 Billy Joe Bob 8 7 Whay type of query do I need to build, any help would be great. Thanks -- Message posted via http://www.accessmo...

populate a DataSet via a LINQ query (Linq to XML)
Is there a way to populate a DataSet via a LINQ query? (Linq to XML) Instead of; DataSet ds = new DataSet(); ds.ReadXml(myfile.xml, XmlReadMode.InferTypedSchema); dataGridView1.DataSource = ds.DefaultViewManager; dataGridView1.DataMember = "myNode"; Anthony Anthony wrote: > Is there a way to populate a DataSet via a LINQ query? > > (Linq to XML) > > Instead of; > DataSet ds = new DataSet(); > ds.ReadXml(myfile.xml, XmlReadMode.InferTypedSchema); > dataGridView1.DataSource = ds.DefaultViewManage...

importing XML doc into SQL Server
Hello, I am trying to import an XML document into SQL Server. I have tried DTS, bulk loading into SQL server and anything else I can think of... The only thing that has worked slightly is : Dim objSQLConn As New SqlConnection(Constants.ConnectionString) Dim objAdapter As SqlDataAdapter Dim objDataRow, objDBRow As DataRow Dim objDSXML As New DataSet() Dim child As Xml.XmlNode Dim objDSDBTable As New DataSet("tblStandardstest") Dim ObjCmdBuilder As SqlCommandBuilder objDSXML.ReadXml("c:/inetpub/wwwroot/olpt7/ACH_STATE_SUBJECT_Ohio_2001_Engli sh.xml") objSQLConn.Open(...

SUM PRODUCT Function
I have an excel sheet regarding the major league baseball draft for the past five years. I have several variables(draft round, position, schooling, level reached, etc). It works well for most of my sumproduct searches. When I try to find out how many people reached the major leagues within some of the variables, it never counts them the right way. It will count maybe 5 when there are probably 25-30 who reached this level. How can I ensure that it counts the criteria for the sumproduct searches correctly? -- Jhova5 -----------------------------------------------------------------------...

Need Linq Help
I need linq help. I have a dictionary where the keys are strings and I need to select from that dictionary into another dictionary where the first two characters of the key match a parameter. For exmaple here is the code: Dictionary<string, string> origDict =3D new Dictionary<string, string>(); origDict.Add(""BSOne", "1") origDict.Add(""BSTwo", "2") origDict.Add(""PLOne", "11") origDict.Add(""PLTwo", "22") I need to select into a new dictionary only where the keys star...

Linq to XML?
I have five items of information I need to extract from XML covering upwards of 25 separate devices. I'm obtaining these values via five Linq to XML queries as follows: IEnumerable<string> EIDs = (from env in xdoc.Root.Elements("packet"). Elements(ns1 + "data").Elements(ns2 + "server_group"). Elements(ns2 + "env") select (string)env.Element(ns3 + "eid")); IEnumerable<int> IDs = (from env in xdoc.Root.Elements("packet"). Elements(ns1 + "data").Elem...

How do I use istext with a sum formula?
I have to add three cells together to get a total. The second cell could possible have text in it. How do I use the istext formula? The SUM function ignores text values, so you could use =SUM(A1:C1) or =SUM(A1,B1,C1) Both formulas will ignore any non-numeric values. However, if a cell has an error in it (e.g., #VALUE), SUM will return that error. To sum a range that has error values, use =SUM(IF(ISERROR(A2:C2),0,A2:C2)) Since this is an array formula, you *must* press CTRL SHIFT ENTER rather than just ENTER when you first enter the formula and whenever you edit it later. If you do th...

xml into collections
Hi all, we have an xml file. Based on this file we have to generate menu. This xml file changes every day. We are loading the xml file into the application memory and transforming the data of xml file into collections (using classes). 1. Pumping the whole xml data into collections is the correct way or not? 2. As xml is already a structured representation of data, is it necessary to convert the data into collections? 3. If we converted the data into collections, is it true we can get better performance rather than querying the xml everytime? 4. Querying the xml everytime consumes more ti...