YWah
YWah

Reputation: 579

Collect strings after a foreach loop

Is it possible to collect the strings after a foreach loop? For example:

StringCollection col = new StringCollection();
XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name");
foreach (XmlNode skillNameNode in skillNameNodeList) 
{
  skillsName=skillNameNode.Attributes["value"].Value;  
}

col.Add(skillsName); //Return System.Collections.Specialized.StringCollection

I want to collect each skillsName and put them in a collection or a list so that I can use it later. Is it correct to use StringCollection? Or any other better suggestion?

Upvotes: 0

Views: 207

Answers (3)

tmutton
tmutton

Reputation: 1101

List<string> myList = new List<string>();
XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name");
foreach (XmlNode skillNameNode in skillNameNodeList) 
{ 
  myList.Add(skillNameNode.Attributes["value"].Value);
}

There may be a neater way to do it via linq. It would be something like the below (disclaimer: not tested).

var myList = SkillXML.GetElementsByTagName("name").Cast<XmlNode>().Select(n => n.Attributes["value"].Value).ToList();

Upvotes: 0

Huusom
Huusom

Reputation: 5912

You can also create the list directly using LINQ

var list =
 SkillXML.GetElementsByTagName("name")
 .Cast<XmlNode>()
 .Select(n => n.Attributes["value"].Value)
 .ToList();

Upvotes: 2

DGibbs
DGibbs

Reputation: 14618

Yep, you need to do the adding within the loop. I'd use a List<string> as it supports LINQ:

XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name");
List<string> skills = new List<string>();

foreach (XmlNode skillNameNode in skillNameNodeList) 
{
     skills.Add(skillNameNode.Attributes["value"].Value);
}

Upvotes: 2

Related Questions