1
\$\begingroup\$

I have this code:

if(listObj.Any(x => x.id < 0))
{
    foreach(ModelClass item in listObj)
    {
        if(item.id < 0)
        {
            // code to create a new Obj in the database
        }
    }
}

But, should I use like this?

foreach(ModelClass item in listObj)
{
    if(item.id < 0)
    {
        // code to create a new Obj in the database
    }
}

NOTE: It's unusual to exist id < 0 (I use this to create a temp id for manipulation in the page), but there is a possibility.


Extra info that I found:

\$\endgroup\$
1
  • \$\begingroup\$ us a simple for loop and not a foreach and remove any linq code if you need performance and if you need to do it really fast use an unmanaged for loop \$\endgroup\$ – Walter Vehoeven Jan 6 at 10:16
5
\$\begingroup\$

Use .Where extension method to filter the records you need:

foreach(ModelClass item in listObj.Where(x => x.id < 0))
{
    // code to create a new Obj in the database
}
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Related: LINQ extension methods - Any() vs. Where() vs. Exists() \$\endgroup\$ – Michel Ayres Jun 21 '13 at 17:55
  • \$\begingroup\$ that would kill performance as you effectively create a 2nd loop plus an object that needs to be allocated and managed by the GC \$\endgroup\$ – Walter Vehoeven Jan 6 at 10:14
  • \$\begingroup\$ @WalterVehoeven There are no inner loops, the collection is scanned once. There is a certain performance penalty for executing a delegate and having an iterator but in most real-world cases its effect is negligible. \$\endgroup\$ – almaz Jan 12 at 14:46
  • \$\begingroup\$ well you have 2 loops, one in your where linq statement and one in the foreach.LINQ is no "free ride" \$\endgroup\$ – Walter Vehoeven Jan 13 at 5:57
  • \$\begingroup\$ Let's measure it in O notation. The statement is O(N), where N is the number of elements in the listObj. Same as in the original statement. For most scenarios that's what matters. \$\endgroup\$ – almaz Jan 14 at 7:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.