LINQ Where Syntax

c# html-agility-pack linq


I've the following LINQ to fill a datatable from html <tr> tags with the help of HTMLAgilityPack, each tag has one attribute and i need to ignore the innertext of that tag if the attribute value is "rating-col".

tr => tr.Elements("td").
    Select(td => td.InnerText.
        Where(td.Attributes[0].Value != "rating-col")).
        ForEach(row => dt.Rows.Add(row));

without the Where clause things work fine, what am i doing wrong inside the Where clause?

3/6/2013 4:13:34 AM

Accepted Answer

Looks like you were missing a lambda and that one of the Selects was out of order. Also, there was no reason for ToList() or ForEach() here. Your ToList() call made things slower and forced you to use more memory. The only reason you need it is to get at the ForEach() extension, and that doesn't really save you anything here over a normal foreach loop. Plus, while I'm not an expert in that area, I'm given to understand that the ForEach() extension is poor functional style, because it almost assumes you're causing side effects (a big functional no-no). Since linq is heavily inspired by the functional programming paradigm, I try to pay attention to such things.

foreach (var row in nodes.Skip(1)
     .Select(tr => tr.Elements("td")
         .Where(td => td.Attributes[0].Value != "rating-col")
         .Select(td => td.InnerText)
3/6/2013 4:58:59 AM

Popular Answer

Where(td.Attributes[0].Value != "rating-col")) should have a lambda in it ...such as:

Where(c => c.Attributes[0].Value != "rating-col"))

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow