LINQ To SQL: First operator

EmpDetails Table:

LinqTable.png


Code:


To Return the First Element in a Sequence.
 

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
LINQ
{
class Program
{
static void Main(string[] args)
{
DataClassesDataContext dc = new DataClassesDataContext();

EmpDetail empQuery = (from emp in dc.EmpDetails
                      where emp.Dept == "MOSS"
                      select emp).First();
Console.WriteLine("ID :{0}, Name :{1}, Location :{2}, Department :{3}", empQuery.ID, empQuery.Name, empQuery.Location, empQuery.Dept);
Console.ReadLine();
}
}
}

Output:


ID :1, Name :Vijai, Location :Bangalore, Department :MOSS


Alternate method:


DataClassesDataContext dc = new DataClassesDataContext();
EmpDetail empQuery = dc.EmpDetails.First();
Console.WriteLine("ID :{0}, Name :{1}, Location :{2}, Department :{3}", empQuery.ID, empQuery.Name, empQuery.Location, empQuery.Dept);
Console.ReadLine();

Next Recommended Reading LINQ To SQL: Order by operator