Reputation: 45
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
Upvotes: 0
Views: 2258
Reputation: 18155
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.
Upvotes: 1
Reputation: 92
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);
}
}
Upvotes: 1
Reputation: 4808
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);
}
}
Upvotes: 1