Empty variable by foreach

Asked

Viewed 158 times

2

Values are not placed in my variable by foreach, which I do?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Tabela
{
    [Activity (Label = "Result")]           
    public class Result : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            string s, e, n, v;

            StreamReader strm = new StreamReader(Assets.Open("tabela.xml")); 
            XDocument xd = XDocument.Load(strm); 

            var q = from b in xd.Descendants("elemento")
                    where Convert.ToString(b.Element("simbolo")) == "H"
                select new
            {
                simbolo = (string)b.Element("simbolo").Value,
                elemento = (string)b.Element("elemento").Value,                    
                nAtomic = (string)b.Element("nAtomic").Value,
                valencia = (string)b.Element("valencia").Value                   
            };
            TextView es = FindViewById<TextView> (Resource.Id.tl);

            foreach (var a in q)
            {
                s = a.simbolo;
                e = a.elemento;
                n = a.nAtomic;
                v = (string)a.valencia;
            }
            es.Text = s;
            SetContentView (Resource.Layout.Resultado);
        }
    }
}
  • 1

    Put a breakpoint before the foreach and check that the collection q is filled. Note that as it is, each cycle of the foreach will give a new value to its variables, thus losing the previous value.

  • @Lucas has the template of this xml (tables.xml) that can make available?

  • Dude, give me a name for these variables, please.

1 answer

1

This code snippet can help you:

foreach (XmlElement element in elements) {
    string productCode = element.GetAttribute("productCode");
    int quantitySold = Int32.Parse(element.GetAttribute("quantity"));

    Console.WriteLine(quantitySold);

    string xPathExpression = "//items/item[@productCode='" + productCode + "']";
    XmlElement inventoryItem = (XmlElement)inventory.SelectSingleNode(xPathExpression);

    int quantity = Int32.Parse(inventoryItem.GetAttribute("quantity"));
    quantity -= quantitySold;
    inventoryItem.SetAttribute("quantity",quantity.ToString());
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.