First Im a noob in LINQ ! Then, the thing is that I have a Collection that :
I wanted to use Where but I don't like the if
instructions that I have to do... so here is my code :
if (MyCollection.Any(rm => rm.BaseName == rbName))
{
var tmp = MyCollection.First(rm => rm.BaseName == rbName);
}
This works but I really feel like this is not the way I should do it with LINQ... Any suggestion ?
Returns the first element in a sequence that satisfies a specified condition.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
The SingleOrDefault() method does the same thing as Single() method. The only difference is that it returns default value of the data type of a collection if a collection is empty, includes more than one element or finds no element or more than one element for the specified condition.
Element Operators: First & FirstOrDefaultReturns the first element of a collection, or the first element that satisfies a condition. FirstOrDefault. Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
Non-Unique Entity Answer (with exception throwing on multiple instances)
Use SingleOrDefault. This will return the unique item if it exists, null if it doesn't exist or it will throw and exception if there is more than one.
var tmp = MyCollection.SingleOrDefault(rm => rm.BaseName == rbName);
Unique Property Answer (there will never be multiple instances)
If your system is set up so that BaseName
is a unique entity, user FirstOrDefault
, this won't throw an exception if there are multiple as it will stop at the first instance, but the system will be designed so there will never be the same instance, so it would be acceptable (and time reducing).
var tmp = MyCollection.FirstOrDefault(rm => rm.BaseName == rbName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With