Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix Any() and First() in LINQ?

Tags:

c#

linq

First Im a noob in LINQ ! Then, the thing is that I have a Collection that :

  1. either does not contain my ID (string)
  2. or contains it ONLY once

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 ?

like image 797
Guillaume Slashy Avatar asked Jan 10 '12 09:01

Guillaume Slashy


People also ask

What is use of first () in LINQ?

Returns the first element in a sequence that satisfies a specified condition.

What is difference between FirstOrDefault and SingleOrDefault in LINQ?

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.

What is difference between single and SingleOrDefault in LINQ?

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.

What is first and FirstOrDefault in LINQ?

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.


1 Answers

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);
like image 53
Lloyd Powell Avatar answered Nov 04 '22 04:11

Lloyd Powell