0

I deserialized an xml file in order to perform some treatment and write results in an other xml file,

Deserialization :

        XmlSerializer deserializer = new XmlSerializer(typeof(Network));
        TextReader reader = new StreamReader(@"path\XmlFile.xml");
        object obj = deserializer.Deserialize(reader);
        Network XmlData = (Network)obj;
        reader.Close();

I got "ROUTES" elements of my xml in a list

Some content of the "ROUTES" list

Now I want to browse this list to compare a string that is given on the command line (OriginSignal) to the value of the child element "ENTRANCESIGNAL" of each "ROUTE" element of the list

I tried this :

        string OriginSignal = null;
        Console.WriteLine("");
        OriginSignal = Console.ReadLine();
        foreach (var route in XmlData.ROUTES)
        {
            if (OriginSignal.Equals(XmlData.ROUTES[].ENTRANCESIGNAL))
            {
                Console.WriteLine(XmlData.ROUTES[].ID);     
            }
        }
        Console.ReadLine();

I don't know what to put in ROUTES[] as index.

I tried with XmlData.ROUTES[route] but I'm getting an error Argument 1: cannot convert from 'XmlData.ROUTES' to 'int'

I'm a beginner in c# programming, so I would like to have some help to implement this

3 Answers 3

1

You are using the foreach loop here. foreach doesn't use an index, instead it returns an element in the collection during each iteration. In this case, route variable contains an element in the collection during each iteration. You need to compare the element with OriginalSignal.

   foreach (var route in XmlData.ROUTES)
   { 
    if(OriginalSignal.Equals(route.ENTRANCESIGNAL))
    {
    Console.WriteLine(route.ID);  
    }
   }

Follow here to learn more on foreach loops.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use an index for your array as you're using a foreach loop, which instantiates your route variable with the next element in the array for each iteration of the loop. You just need to use your variable:

foreach (var route in XmlData.ROUTES)
{
    if (OriginSignal.Equals(route.ENTRANCESIGNAL));
    {
        Console.WriteLine(route.ID);     
    }
}

Comments

1

This should do it if I understood the question correctly. You don't have to use an index. A foreach basically loops through all of the elements in the XmlData.ROUTES and the var route is always the current item.

  foreach (var route in XmlData.ROUTES)
    {
        if (String.Equals(OriginSignal, route.ENTRANCESIGNAL)
        {
            Console.WriteLine(route.ID);     
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.