1

I basically try to use htmlagilitypack to parse a piece of html and use linq to put it into object for uses with other piece of my code. I've got below two code snippets where #1 uses linq and does not work, but #2 uses a for loop and works.

Two pieces of codes are nearly identical except for the usage of linq. In that sense, I guess I have missed something in linq that prevents me from making it work?

Appreciate if anyone can help me take a look

  1. using linq - it does not work. res ends up being null

    res = from li in ul.Elements("li").Where(i => GetClass(i) != "titles-h")
    select new Post()
    {
        title = li.Element("h2").InnerText,
        // ....
    };
    
  2. no linq - it works

    foreach (var li in ul.Elements("li"))
    {
        if (GetClass(li) != "titles-h")
            ress.Add(new Post()
              {
                  title = li.Element("h2").InnerText,
                 // ....
              });
    }
    

implementation of GetClass

static string GetClass(HtmlNode n)
{
    if (n.Attributes["class"] != null)
        return n.Attributes["class"].Value;
    else
        return "";
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
user915383
  • 11
  • 1
  • Your LINQ looks OK, but be aware that `res` ends up being not a collection of `Post` object but a _query to generate those objects from `ul`_. If `ul` is changed by the time you use `res`, you will get different results. Try calling `ToList` to immediately gerenate a list of the results. – Rawling Dec 03 '12 at 15:52
  • Thanks Rawling. After some thoughts this could very likely to be the cause since I put all things in a try catch block while `ul` is being declared there. I don't have chance to try right now but I'll give it a shot as soon as I have access to my code. – user915383 Dec 04 '12 at 16:41
  • @Rawling, how do I mark your question as an answer? – user915383 Dec 04 '12 at 16:41
  • If you try calling `ToList` and it works for you, let me know and I'll type this up as a proper answer that you can accept. If not, I won't bother :p – Rawling Dec 04 '12 at 16:47

0 Answers0