C#: Combining AddRange() and Lambda Expression

c# html-agility-pack lambda

Question

I have a Collection of nodes, specifically a collection of HTMLAgilityPack.HTMLNodeCollection nodes. I know I can extract and store information from the nodes by doing:

List<string> nodesList = new List<string>();

var nodes = myFile.DocumentNode.SelectNodes(file_path);
foreach (var node in nodes)
    nodesList.Add(node.InnerText);

However, what I would like to do is apply AddRange(), rather than add the items in a foreach loop. I'm trying to use a lambda expression to do this, but I'm not familiar enough with lambda expressions to do it properly. I'm trying to combine something like

nodesList.AddRange( string[] arr = x => nodes.ToArray()[x].InnerText );

I know that makes no syntactical sense, but I'm not sure if can even do this. I would like to just Cast<string>() the collection, but I need to extract the text from each node.

Any ideas on how to put this into an AddRange() expression?

Accepted Answer

You're looking for IEnumerable.Select():

nodesList.AddRange(nodes.Select(node => node.InnerText))



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why