First()
Member
Member
ID | Name | Year | Address | Income | UserName |
1 | PQR | 2010-2011 | C | 50000 | S123 |
2 | PQR | 2012-2013 | C | 180000 | S123 |
3 | XYZ | 2013-2014 | B | 200000 | S789 |
4 | ABC | 2013-2014 | A | 350000 | S253 |
Var x=(from m in Member
Where m.UserName=’S000’
Select m.Name,m.Income,m.Year ).First()
In The Member table There Is no Such Record Which Will Match the expression so Above Query will Throw: InvalidOperationException: Sequence contains no elements
Var x=(from m in Member
Where m.UserName=’s123’
Select m.Name,m.Income,m.Year).First()
Then You Will get The Result Like:
Var x=(from m in Member
Where m.UserName=’s123’
Select m.Name,m.Income,m.Year).First()
Then You Will get The Result Like:
PQR | 2010-11 | 50000 | S123 |
- First() returns First Element Of Sequence.
- First() throws Exception when There IS No element Presnt In Table.
FirstORDefault():
When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null)
Var x=(from m in Member
Where m.UserName=’S000’
Select m.Name,m.Income,m.Year ).FirstOrDefault()
In The Member table There Is no Such Record Which Will Match the expression so Above Query will Return Default value as Null but Not An Exception
We Can Handle This Exception In C# by using try Catch like:
try
{
Var x=(from m in Member
Where m.UserName=’S000’
Select m.Name,m.Income,m.Year ). FirstOrDefault ()
If(x!=null)
{
Console.WriteLine(x.Name);
}
else
{
Console.WriteLine("No Record Found");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null)
Var x=(from m in Member
Where m.UserName=’S000’
Select m.Name,m.Income,m.Year ).FirstOrDefault()
In The Member table There Is no Such Record Which Will Match the expression so Above Query will Return Default value as Null but Not An Exception
We Can Handle This Exception In C# by using try Catch like:
try
{
Var x=(from m in Member
Where m.UserName=’S000’
Select m.Name,m.Income,m.Year ). FirstOrDefault ()
If(x!=null)
{
Console.WriteLine(x.Name);
}
else
{
Console.WriteLine("No Record Found");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
- FirstOrDefault () returns First Element Of Sequence.
- FirstOrDefault () does not throws Exception when There IS No element Present in Table.
No comments :
Post a Comment