In Linq, what's the difference between .FirstOrDefault and .SingleOrDefault - linq

I don't know the difference between FirstOrDefault and SingleOrDefault. When should I use the first and when should I use the second?

FirstOrDefault() is for when zero or more results are expected to be present in the input collection and the call returns the first item if there are multiple results, Default if none.
SingleOrDefault() is for when zero or one result is expected in the input collection and the call returns the one result if exactly one result is present, Default if no results and exception if more than one result.

SingleOrDefault will throw a "Sequence contains more than one element" exception if more than one item exists.

firstordefault it will take number of rows but will just return first one of it if it is
null it can handle the exception
First it will take number of rows but will just return first one of it if it is
null it will throw the exception
singleordefault it will take only one row but will return it can handle exceptions if it is null
single it will take only one row but will return it & cannot handle exceptions
If your result set returns 0 records:
SingleOrDefault returns the default value for the type (e.g. default for int is 0)
FirstOrDefault returns the default value for the type
If you result set returns 1 record:
SingleOrDefault returns that record
FirstOrDefault returns that record
If your result set returns many records:
SingleOrDefault throws an exception
FirstOrDefault returns the first record
Conclusion:
If you want an exception to be thrown if the result set contains many records, use SingleOrDefault.
If you always want 1 record no matter what the result set contains, use FirstOrDefault

Related

RethinkDB: Get only one record from cursor/selection

If I have a query that returns multiple results, how do I get a single element from the selection?
e.g.
r.db("test").table("things") // returns an array of things. I want one of them
Using limit(1) is not what I want because that returns an array.
Rethink DB supports getting the nth element so the query should be:
r.db("test").table("things").nth(0)
In the event that there are no elements, the above will fail with:
Index out of bounds: 0
The solution to this is to return a default object (null in my case) if no element exists.
r.db("test").table("things").nth(0).default(null)

Spring jdbcTemplate executing query

I have a strange problem ,
My Query looks like below.
String tokenQuery = "select id from table
where current_timestamp between
creation_time and (creation_time + interval '10' minute)
and token = '"+Token+"'";
But when I run, jdbcTemplate.queryForLong(tokenQuery) , no matter what , it always throws EmptyDataAccessException.
I am executing this in Oracle
Can we not append dynamic values to string and then pass it as a query and execute ?
What could be the issue ?
I assume that what you get is in fact an EmptyResultDataAccessException. The javadoc of this exception says:
Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned.
That simply means that the query is executed fine, and is supposed to return one row, but doesn't return any. So no row satisfies the criteria of your query.
If that is expected, then catch the exception, or use a method that returns a list rather then returning a single value. That way, you can test if the returned list is empty.
That said, you should use a parameterized query instead of concatenating the token like you're doing. This would prevent SQL injection attacks. It would also work even if the token contains a quote, for example.

How to convert iqueryable<string> to string in linq?

i have the following code snippet.
in which i just want to return PartyName as a string.
but i get the error:"Cannot implicity convert type 'System.Linq.Iqueryable to string"
if i want to return only string then what to do?
please help me.
return objDatabase.FAPARs
.Where(f => (f.PARTY_CODE == "P003"))
.Select(f => f.PARTY_NAME);
An IQueryable<string> represents a query which could return any number of strings. You want one string - so you need to decide what to do in various situations:
What do you want to happen if the query has no results?
What do you want to happen if the query has one result? (I assume this is simple :)
What do you want to happen if the query has more than one result?
The set of methods which allow you to determine all of this are:
Single - fail if there isn't exactly one result
SingleOrDefault - fail if there's more than one result, return null if there are no results
First - fail if there are no results, return the first of many
FirstOrDefault - return null if there are no results, or the first of many
Last - fail if there are no results, return the last of many
LastOrDefault - return null if there are no results, or the last of many
In each case, "fail" means "throw an exception". (IIRC it's always InvalidOperationException, at least in LINQ to Objects, but I could be wrong.)
So if you're querying by an ID which must exist (i.e. it's a bug if it doesn't) then Single is probably appropriate. If you're querying by an ID which may not exist, then use SingleOrDefault and check whether the return value is null. If you're not querying by an ID, you probably want to use FirstOrDefault or just iterate over the results.
(Note that the default value being null is due to this being a query returning strings, and string being a reference type. In general it's the default value of the element type - so if you had an IQueryable<int>, the default returned would be 0.)
Try
return objDatabase.FAPARs .Where(f => (f.PARTY_CODE == "P003")) .Select(f => f.PARTY_NAME).SingleOrDefault();
Try this:
return objDatabase.FAPARs.Where(f => (f.PARTY_CODE == "P003")).Single(f => f.PARTY_NAME);
return objDatabase.FAPARs.FirstOrDefault(f => f.PARTY_CODE.Equals("P003")).PARTY_NAME
return objDatabase.FAPARs.OfType<FAPAR>()
.Where(f => (f.PARTY_CODE == PartyCode && f.COMP_NO == ComCode))
.Select(f => f.PARTY_NAME).SingleOrDefault();

querying a list - returns only one value

I have created a structure and list.
public struct CarMake
{
public string name;
public string id;
}
I added structure objects to this (carMakers) and am trying to query
string selCar = from c in carMakers
where c.name == selectedCarMfgName
select c.id;
I am getting an error near select statement- cannont implicity convert IEnumerable to string. I know that query returns only one value, that's why I have like that.
thanks !
string selCar = (from c in carMakers
where c.name == selectedCarMfgName
select c.id).SingleOrDefault();
Your query returns a collection (with one element). You should use Single() (or SingleOrDefault()) to get that one item. If the query can return more than one result, you should look into First() ( or FirstOrDefault())
Pay attention to the error message. It probably says something like
"cannot implicitly convert IEnumerable<string> to string."
The results of a query of a sequence is another sequence, an IEnumerable<T>. You may know that you expect only one result, but that's not what the query does. To obtain only one result, you can optionally include another extension method on the end.
yourQuery.First();
yourQuery.FirstOrDefault();
yourQuery.Single();
yourQuery.SingleOrDefault();
The difference in these is that the First* variations can work with sequenes with many elements, whereas the Single* variations will throw exceptions if more than one element is present. The *OrDefault variations support the concept of no matching elements, and returns the default value for the type (null in the case of classes, a default value (such as 0 for int) for structs).
Use the version that conforms to your expectation. If you expect one and only one match, prefer Single. If you only care about one out of arbitrarily many, prefer First.
carMakers.Add(new CarMake() { name = "Audi", id = "1234" });
string selCar =(from c in carMakers
where c.name == "Audi"
select c.id).FirstOrDefault();
Output- 1234
I would refactor my query slightly:
var selCar = carMakers.Single(c => c.name == selectedCarMfgName).id;
This assumes you know that the car is in the list. If not, use SingleOrDefault and check the return before getting the id.
I've not done too much with LINQ but because you are selecting into a string you may need to use FirstOrDefault as your statement could return back more than one value yet your string can only hold one.
First will return null value I think if nothing is found but FirstOrDefault will return you a blank string.

LINQ - Sequence contains no elements

I am using a LINQ query as below.
object.collection.where(t => t.id.Equals("2")).First();
I am getting the error "Sequence contains no elements". Why does the result throw an error when the result contains no elements? Should it not return null when no results are found? That is what happens when using SQL.
It's working as designed. The First() method is to be called when it's known at least one row will be returned. When this isn't the case, call FirstOrDefault().
object.collection.where(t => t.id.Equals("2")).FirstOrDefault();

Resources