Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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