0
Reply

List problem

fudge me

fudge me

May 19 2009 6:58 PM
2k
At the moment i read in an xml file, i put em in a list and sort it at the second attribute called "name". After this i want to get the first value called "id" back to the front. At the moment I use an '@' character to substring it back to the front like the code below, but I want a solution without the @

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XmlDocument document;
XmlNodeList nodelist;
List<string[]> list = new List<string[]>();

//make xmldocument & read the xml values
document = new XmlDocument();
document.Load("personen.xml");
nodelist = document.SelectNodes("/personen/persoon");
foreach (XmlNode node in nodelist)
{
string id = node.Attributes.GetNamedItem("id").Value;
string naam = node.ChildNodes.Item(0).InnerText;
string voornaam = node.ChildNodes.Item(1).InnerText;
list.Add(naam + ", " + voornaam + "@" + id);
}

//sort de list
list.Sort();

//write the list to a text file
StreamWriter SW;
SW = File.CreateText("personen.txt");
foreach (string[] line in list)
{
//use the '@' sign to sort the list but get the id to the front later on
int index = line.IndexOf('@');
string sub1 = line.Substring(index + 1);
string sub2 = line.Substring(0, index);
SW.WriteLine(sub1 + ", " + sub2);
}
SW.Close();
}
}
}

I tried to solve this like the code below, but then my list.sort() doesn't work anymore

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XmlDocument document;
XmlNodeList nodelist;
List<string[]> list = new List<string[]>();

//make xmldocument & read the xml values
document = new XmlDocument();
document.Load("personen.xml");
nodelist = document.SelectNodes("/personen/persoon");
foreach (XmlNode node in nodelist)
{
string[] persoon = new string[3];
persoon[0] = node.ChildNodes.Item(0).InnerText;
persoon[1] = node.ChildNodes.Item(1).InnerText;
persoon[2] = node.Attributes.GetNamedItem("id").Value;
list.Add(persoon);
}

//sort de list
list.Sort();

//write the list to a text file
StreamWriter SW;
SW = File.CreateText("personen.txt");
foreach (string[] line in list)
{
SW.WriteLine(line[0] + line[1] + line[2]);
}
SW.Close();
}
}
}

Thanks a lot for reactions