public void GeneralLinqToSql() { EmployeesDatabaseDataContext context = new EmployeesDatabaseDataContext(); // IQueryable<Employee> employees = from e in context.Employees where e.JobDescription.JobDescription1 == "Developer" orderby e.Name descending select e; IQueryable<Employee> employees2 = context.Employees.Where(e => e.JobDescription.JobDescription1 == "Developer") .OrderByDescending(e => e.Name) .Select(e => e); // Select is actually OPTIONAL // Single selection Employee employee1 = context.Employees.Where(e => e.JobDescription.JobDescription1 == "Developer") .OrderByDescending(e => e.Name) .Select(e => e) .First(); // No corresponding keyword in comprehension syntax }
public void LinqToAnonymousTypes() { EmployeesDatabaseDataContext context = new EmployeesDatabaseDataContext(); // var keyword has a key role // Single selection var employees1 = context.Employees.Where(e => e.JobDescription.JobDescription1 == "Developer") .OrderByDescending(e => e.Name) .Select(e => new { FirstName = e.Name }); }
/// <summary> /// Allows you to continue using a query after using Select. /// </summary> public void UsingInto() { EmployeesDatabaseDataContext context = new EmployeesDatabaseDataContext(); var output = from a in context.Employees where a.Name == "David" select a into p where p.Name.Length < 5 select p; // Grouping var output2 = from a in context.Employees group a by a.JobDescriptionId into b orderby b.Key ascending select b; // Composite Key grouping requires an anonymous type var output3 = from a in context.Employees group a by new { a.Name, a.JobDescriptionId }; }
/// <summary> /// Let allows variables to be introduced into a query to help with reuse /// </summary> public void UsingLet() { EmployeesDatabaseDataContext context = new EmployeesDatabaseDataContext(); var output = from a in context.Employees let lname = a.Name.ToLower() where lname == "david" select lname; }
public void LinqToSqlSample() { EmployeesDatabaseDataContext context = new EmployeesDatabaseDataContext(); IQueryable<Employee> employees = from e in context.Employees where e.JobDescription.JobDescription1 == "Developer" select e; var output = employees.ToList(); }