The question: if you use a linq query over a list of elements and you want to select only the first element, using the First extension, does the processing continue after hitting a match? Why is this important? it’s because the query might be very heavy and you don’t really need to process all elements, only if an element matches your query.
Here is the test:
class Program
{
static void Main(string[] args)
{
List<Element> lst = new List<Element>();
lst.Add(new Element("1"));
lst.Add(new Element("2"));
lst.Add(new Element("3"));
lst.Add(new Element("4"));
lst.Add(new Element("5"));
var res = (from e in lst
select e.Name).First();
Console.ReadKey();
}
}
class Element
{
private string m_name;
public string Name
{
get { Console.WriteLine(m_name); return m_name; }
}
public Element(string name) { this.m_name = name; }
}
And the answer: Linq will stop after the first element corresponding to your query is found.



Entries (RSS)