简体   繁体   中英

Simple code to get specific item from a list

I have a list of a tags. I want to get an a tag which contains a string. I used the below code and everything work fine.

string mainLink = "";
List<HtmlNode> dlLink = new List<HtmlNode>();
dlLink = doc.DocumentNode.SelectNodes("//div[@class='links']//a").ToList();

foreach (var item in dlLink) {
  if (item.Attributes["href"].Value.Contains("prefile"))
   {
     mainLink = item.Attributes["href"].Value;
   }
}

but I want to write a simple code

var dlLink = doc.DocumentNode.SelectNodes("//div[@class='link']//a").ToList().Where(x => x.Attributes["href"].Value.Contains("prefile")).ToList().ToString();

But it does not work and I get nothing.

Your foreach is setting mainLink string, but your linq chain is using ToString on a List result.

Converting your code, you will have something like this:

mainLink  = doc.DocumentNode.SelectNodes("//div[@class='links']//a")
                            .Where(item => item.Attributes["href"].Value.Contains("prefile"))
                            .Select(item => item.Attributes["href"].Value)
                            .Last(); 

I used Select to get only the href values, and getting the last as your foreach did, maybe you need to validate this last step, use a LastOrDefault , First , etc.

You can also use the Last or First instead of the Where condition:

mainlink = doc.DocumentNode.SelectNodes("//div[@class='links']//a")
                           .Last(item => item.Attributes["href"].Value.Contains("prefile"))
                           .Attributes["href"].Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM