views:

341

answers:

2

I'm looking for a simple solution to replace my standardized junk way of validating whether a record exists before attempting to retrieve the data. Currently, whenever one of my methods are called, I do something to the effect of...

private Record DoSomething(int id)
{
   if(data.Records.Count(q=>q.Id==id) > 0)
   {
      return data.Records.First(q=>q.Id==id);
   }
   return null;
}

...where I always check the count of the records to determine the existence of a record. There has to be a more "elegant" way of doing this, without calling the database twice. Does anyone have any ideas?

Thanks! George

+5  A: 

There are a lot of clean ways to handle this. If you want the first Record corresponding to id you can say:

Record record = data.Records.FirstOrDefault(r => r.Id == id);
if(record != null) {
    // record exists
}
else {
    // record does not exist
}

If you only want to know if such a Record exists:

return data.Records.Any(r => r.Id == id); // true if exists

If you want a count of how many such Record exists:

return data.Records.Count(r => r.Id == id);

If you want an enumeration (IEnumerable<Record>) of all such Record:

return data.Records.Where(r => r.Id == id);
Jason
I think SingleOrDefault will throw an exception if more than one record is returned. Since it looks like an Id query it is probably safe to assume that SingleOrDefault would be okay, but FirstOrDefault is more general I think.
Mike Two
`Any(r => r.Id == id)` is preferred because it's more efficient (will result in an `EXISTS` instead of a `COUNT`).
JulianR
+1  A: 
Record record = data.Records.FirstOrDefault(q => q.Id == id);
return record;
Mike Two