Click here to Skip to main content
15,944,958 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All

How can i retrieve the last record from database using LINQ method? And how a handle the error if the LINQ table has no records?
Posted
Updated 7-Dec-10 22:40pm
v2

Just call Last()[^]:
var lastItem = yourQuery.Last()
If you think there is a chance your table may be empty, use LastOrDefault()[^] instead. This will return null if nothing is found.
var lastItem = yourQuery.LastOrDefault();
if(lastItem == null)
{
    //Table was empty.
}
Obviously, if your query isn't actually ordered by anything, then the "last" item could be anything.
 
Share this answer
 
v2
For last record :

1. See This[^] (the answer is below the advertisements at this link, you will have to scroll a lot).

2. See This[^]

To handle the error, if table has no records:

Its just on the top of my head, i cant check it at present, so syntax error may be there:

C#
if(tablename.Records.Count >0) //something like this will do
    {
         //write your code
    }


OR

See this[^]


BTW, some googling by you may have saved your and mine lots of time.
(Please accept answer or provide votes if I was helpful)

Anurag
 
Share this answer
 
Comments
Simon P Stevens 8-Dec-10 8:02am    
Your first link doesn't have any answers - Experts exchange only displays answers for free when the referrer is google.
@nuraGGupta@ 15-Dec-10 2:14am    
Yes, i noticed that later on. Apologies for not considering it.
DBs are technically unordered (OK records pretty much come out in the order they went in, but this isn't guaranteed) so if you need a specific order, you must add some way to do this (identity column [e.g. on an integer surrogate key], a custom ordering column, date column etc).
If you do this, you just need the linq to get the record containing the Max value for your ordering column: How to: Find the Maximum Value in a Numeric Sequence
[^].
Note that there should not be any errors if you have no records: the list of entries will merely be empty, unless you call Single(), in which case SingleOrDefault() will be better, and check for "default"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900