This document provides an introduction to LINQ (Language Integrated Query). LINQ allows querying over various data sources using a common SQL-like syntax. It introduces key LINQ concepts like LINQ to Objects, LINQ to SQL, LINQ to XML and language features in .NET that support LINQ like lambda expressions and extension methods. The document also provides examples of standard query operators and using LINQ to query objects, databases and XML documents.
What's LINQ, its advantages, its Operators and examples on some of them, Methods of Writing it.
LINQ to Objects and Collections and Data Source Transformation.
LINQ stands for Language Integrated Query.
A query is an expression that retrieves data from a data source or database.
Retrieve data from different data source like an object collection, sql server database, xml & web service etc.
LINQ Syntax like- var students = dbContext.Students.ToList();
What's LINQ, its advantages, its Operators and examples on some of them, Methods of Writing it.
LINQ to Objects and Collections and Data Source Transformation.
LINQ stands for Language Integrated Query.
A query is an expression that retrieves data from a data source or database.
Retrieve data from different data source like an object collection, sql server database, xml & web service etc.
LINQ Syntax like- var students = dbContext.Students.ToList();
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written, or manipulated.
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
NicheTech Is the best software firm in ahmedabad . We are providing live project training to MCA students . We are also offering ASP.NET Training Ahmedabad , ASP.NET Course Ahmedabad , ASP.NET Classes Ahmedabad.
ASP.NET : http://mcaprojecttraining.com/asp.net_live_training.html
Live Project Training Ahmedabad
http://mcaprojecttraining.com/asp.net_live_training.html
asp.net using c# notes sem 5 ( we-it tutorials ).
Review of .NET frameworks, Introduction to C#, Variables and expressions, flow controls, functions, debugging and error handling, OOPs with C#, Defining classes and class members.
Assembly, Components of Assembly, Private and Shared Assembly, Garbage Collector, JIT compiler. Namespaces Collections, Delegates and Events. Introduction to ASP.NET 4: Microsoft.NET framework, ASP.NET lifecycle. CSS: Need of CSS, Introduction to CSS, Working with CSS with visual developer.
ASP.NET server controls: Introduction, How to work with button controls, Textboxes, Labels, checkboxes and radio buttons, list controls and other web server controls, web.config and global.asax files. Programming ASP.NET web pages: Introduction, data types and variables, statements, organizing code, object oriented basics.
Validation Control: Introduction, basic validation controls, validation techniques, using advanced validation controls. State Management: Using view state, using session state, using application state, using cookies and URL encoding. Master Pages: Creating master pages, content pages, nesting master pages, accessing master page controls from a content page. Navigation: Introduction to use the site navigation, using site navigation controls.
Databases: Introduction, using SQL data sources, GridView Control, DetailsView and FormView Controls, ListView and DataPager controls, Using object datasources. ASP.NET Security: Authentication, Authorization, Impersonation, ASP.NET provider model
LINQ: Operators, implementations, LINQ to objects,XML,ADO.NET, Query Syntax. ASP.NET Ajax: Introducing AJAX, Working of AJAX, Using ASP.NET AJAX
server controls. JQuery: Introduction to JQuery, JQuery UI Library, Working of JQuery
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written, or manipulated.
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
NicheTech Is the best software firm in ahmedabad . We are providing live project training to MCA students . We are also offering ASP.NET Training Ahmedabad , ASP.NET Course Ahmedabad , ASP.NET Classes Ahmedabad.
ASP.NET : http://mcaprojecttraining.com/asp.net_live_training.html
Live Project Training Ahmedabad
http://mcaprojecttraining.com/asp.net_live_training.html
asp.net using c# notes sem 5 ( we-it tutorials ).
Review of .NET frameworks, Introduction to C#, Variables and expressions, flow controls, functions, debugging and error handling, OOPs with C#, Defining classes and class members.
Assembly, Components of Assembly, Private and Shared Assembly, Garbage Collector, JIT compiler. Namespaces Collections, Delegates and Events. Introduction to ASP.NET 4: Microsoft.NET framework, ASP.NET lifecycle. CSS: Need of CSS, Introduction to CSS, Working with CSS with visual developer.
ASP.NET server controls: Introduction, How to work with button controls, Textboxes, Labels, checkboxes and radio buttons, list controls and other web server controls, web.config and global.asax files. Programming ASP.NET web pages: Introduction, data types and variables, statements, organizing code, object oriented basics.
Validation Control: Introduction, basic validation controls, validation techniques, using advanced validation controls. State Management: Using view state, using session state, using application state, using cookies and URL encoding. Master Pages: Creating master pages, content pages, nesting master pages, accessing master page controls from a content page. Navigation: Introduction to use the site navigation, using site navigation controls.
Databases: Introduction, using SQL data sources, GridView Control, DetailsView and FormView Controls, ListView and DataPager controls, Using object datasources. ASP.NET Security: Authentication, Authorization, Impersonation, ASP.NET provider model
LINQ: Operators, implementations, LINQ to objects,XML,ADO.NET, Query Syntax. ASP.NET Ajax: Introducing AJAX, Working of AJAX, Using ASP.NET AJAX
server controls. JQuery: Introduction to JQuery, JQuery UI Library, Working of JQuery
Overview of ASP.NET
An ASP.NET Page
Server Controls
User Controls
Validation
Master Pages
Themes & skins
Page Cycle Events
Menu, Navigation & Sitemaps
Some cool new ASP.NET 2 Server Controls
slides contains all about the ASP.NET MVC 5 based contents, and hopefully this will also guide you how to a write the MVC program using .NET Technology
Topics Covered
==============================
Overview of .NET
Overview of ASP.NET
Creating an ASP.NET Web Form
Adding Event Procedures
Validating User Input
Agenda:
Getting Started with Standard Query
Operators
Language features supporting the LINQ Project like:
Lambda Expressions and Expression Trees
Extension Methods
Deferred Query Evaluation
Then touch on XLINQ and DLINQ
C# 7.x What's new and what's coming with C# 8Christian Nagel
C# is extended in a fast pace – with new features allow to reduce the code you need to write, offer more safety, and gives better performance – and you still write safe code. In this session you are introduced to the new C# 7.0-7.3 features including tuples and pattern matching, and learn about the features planned with C# 8.0 such as nullable reference types, extensions for pattern matching, and the new switch expression.
To assess the quality of PVS-Studio C# diagnostics, we test it on a large number of software projects. Since projects are written by different programmers from different teams and companies, we have to deal with different coding styles, shorthand notations, and simply different language features. In this article, I will give an overview of some of the features offered by the wonderful C# language, as well as the issues that one may run into when writing in this language.
Esoft Metro Campus - Diploma in Information Technology - (Module IX) Programming with C#.NET
(Template - Virtusa Corporate)
Contents:
Introduction to .NET Framework
.NET Framework Platform Architecture
Microsoft Visual Studio
C# Language
C#, VS and .NET Framework Versions
Your First C# Application
Printing Statements
Comments in C#
Common Type System
Value Types and Reference Type
Variables Declaration in C#
Type Conversion
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
Switch Statement
While Loop
Do While Loop
For Loop
Arrays
Accessing Arrays using foreach Loop
Two Dimensional Arrays
Classes and Objects in C#
Inheritance in C#
Partial Classes
Namespaces
Windows Forms Applications
Using Buttons, Labels and Text Boxes
Displaying Message Boxes
Error Handling with Try… Catch… finally…
Using Radio Buttons
Using Check Boxes
Using List Boxes
Creating Menus
Creating ToolStrips
MDI Forms
Database Application in C#
Creating a Simple Database Application
SQL Insert / Update / Retrieving / Delete
SQL Command Execute Methods
Data Sets
Introduction, Technologies included in ajax,
Ajax Evolution,
Pro’s and Con’s,
Beginners Problem?,
Types and choices of request,
Ajax on hands (Example),
Global Ajax Event Handlers,
Helper Functions,
Low Level interface,
Shorthand Methods for Ajax request.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
2. INDEX
Introduction to LINQ
Why LINQ?
Language features supporting the LINQ project
Getting started with standard query operators
LINQ to Objects
Beyond basic in-memory queries
Getting started with LINQ to SQL
Peeking under the covers of LINQ to SQL
Introducing LINQ to XML
3. INTRODUCTION TO LINQ
Linq is short for Language Integrated Query.
We use the term language-integrated query to indicate
that query is an integrated feature of the developer's
primary programming languages (for example, Visual C#,
Visual Basic).
Component of .NET Framework 3.5
It is a set of methods that are defined by the
Enumerable and Queryable classes.
4. LANGUAGE INTEGRATED QUERY (LINQ)
VB C# Others…
.NET Language-Integrated Query
LINQ enabled data sources
LINQ enabled ADO.NET
LINQ
LINQ LINQ LINQ LINQ
To Objects
To DataSets To SQL To Entities To XML
<book>
<title/>
<author/>
<price/>
</book>
Objects Relational XML
5. QUERY WITHOUT LINQ
Objects using loops and conditions
foreach(Customer c in customers)
if (c.Region == "UK") ...
Databases using SQL
SELECT * FROM Customers WHERE Region='UK‘
XML using XPath/XQuery
//Customers/Customer[@Region='UK']
6. ADO WITHOUT LINQ
SqlConnection c = new SqlConnection(…);
c.Open();
SqlCommand cmd = new SqlCommand(
@”SELECT c.Name, c.Phone Query in
FROM Customers c quotes
WHERE c.City = @p0”);
Arguments loosely
cmd.Parameters[“@po”] = “London”;
bound
DataReader dr = c.Execute(cmd);
While(dr.Read()){
Results loosely
string name = r.GetString(0); bound
string phone = r.GetString(1);
Datetime date = r.GetDateTime(2);
} Compiler cannot
help catch
r.Close(); mistakes
7. LIMITATIONS
o Several steps and verbose code are required.
o Database queries bypass all kinds of compile-time checks.
o The SQL we write for a given DBMS is likely to fail on a
different one.
8. ADVANTAGES OF USING LINQ
Works with any data source.
Compile-time syntax checking, and debugging support.
IntelliSense, Design time support.
Same basic syntax for different types of data sources.
Providing designer tools that create object-relational
mappings.
9. THE SYNTAX
Starts with
from
Zero or more from,
join, let, where, or
from id in source orderby
{ from id in source |
join id in source on expr equals expr [ into id ] |
let id = expr |
Ends with
where condition | select or group
by
orderby ordering, ordering, … }
select expr | group expr by key
[ into id query ]
Optional into
continuation
11. LANGUAGE FEATURES
SUPPORTING THE LINQ PROJECT
Lambda expressions
Extension methods
Initialization of objects and collections in expression context
Local types inference
Anonymous types
Lazy evaluation
+Query Expressions
= LINQ
12. LAMBDA EXPRESSIONS
Express the implementation of a method and the
instantiation of a delegate from that method; they have the
form:
c => c + 1
which means a function with an argument, that returns the
value of the argument incremented by one
The parameters of a lambda expression can be explicitly or
implicitly typed.
13. Examples of lambda expressions
x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console.WriteLine() // No parameters
A lambda expression is a value, that does not have a type but can be
implicitly converted to a compatible delegate type
delegate R Func<A,R>(A arg);
Func<int,int> f1 = x => x + 1; // Ok
Func<int,double> f2 = x => x + 1; // Ok
Func<double,int> f3 = x => x + 1; // Error – double cannot be
//implicitly converted to int
14. EXTENSION METHODS
Extend classes that you could not modify.
They are defined as static methods of other classes that
take at least one parameter, and the first parameter has
the type of the class it extends, but preceded by the
keyword this
15. EXTENSION METHODS (C#)
Extension
method
namespace MyStuff
{
public static class Extensions
{
public static string Concatenate(this IEnumerable<string>
strings,
string separator) {…}
}
}
Brings extensions into
scope
using MyStuff;
string[] names = new string[] { "Jenny", "Daniel",
"Rita" }; obj.Foo(x, y)
string s = names.Concatenate(", ");
XXX.Foo(obj, x, y)
IntelliSense!
16. Example of Extension Method:
public static int VowelCount(this String source)
{
int count = 0;
List<char> vowels = new List<char>() { 'a', 'e', 'i', 'o', 'u', 'A‘,'E', 'I', 'O', 'U' };
foreach (char c in source)
{
if (vowels.Contains(c))
count++;
}
return count;
}
string name = “extension”;
int count = name.VowelCount();
17. INITIALIZATION OF OBJECTS AND
COLLECTIONS IN EXPRESSION
CONTEXT
Object initializers let you assign values to any accessible fields or
properties of an object at creation time without having to explicitly
invoke a constructor.
Example:
private class Cat
{
// Auto-implemented properties.
public int Age { get; set; }
public string Name { get; set; }
}
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
18.
19. Collection Initializers
Collection initializers let you specify one or more element intializers
when you initialize a collection class that implements IEnumerable.
Two simple collection intializers
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };
The following collection initializer uses object initializers to initialize
objects of the Cat class
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
20. Anonymous Types, Implicitly Typed variables
An anonymous type has no name and is generated by the compiler
based on the initialization of the object being instantiated.
var results = from employee in employees
join contact in contacts
on employee.Id equals contact.Id
select new {
employee.FirstName, employee.LastName, contact.City };
the part at “select new”, it’s not using any class name there to
initialize, but it’s there and it’s anonymous
That is the purpose of the var keyword. It infers the type of the
object based on the data type with which it has been intialized
21. LOCAL VARIABLE TYPE INFERENCE (C#)
int i = 666;
string s = "Goodbye";
double d = 3.14;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new
Dictionary<int,Order>();
var i = 666;
var s = "Goodbye";
var d = 3.14;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();
“The type on the
right hand side”
22. • Variable type inferred from initialiser
Integer
String
var x = 666
var s = “Bye" Double
var d = 3.14
var numbers = new Integer() {1, 2, 3}
var orders = new Dictionary(Of Integer, Order)()
23. LAZY EVALUATION
LINQ follows a lazy evaluation model
Queries execute not when constructed, but when enumerated.
This means you can build up a query in as many steps as you like, and it
won't actually hit the server until you eventually start consuming the
results.
var query = db.Customers.Where (c => c.Name.StartsWith ("A")); query =
query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);
foreach (string name in result) //Only now is the query executed!
Console.WriteLine (name);
24. C# 3.5 LANGUAGE INNOVATIONS
var contacts = Query
expressions
from c in customers
where c.City == "Hove"
Local variable select new { c.Name, c.Phone };
type inference
Lambda
expressions
var contacts =
customers
.Where(c => c.City == "Hove")
.Select(c => new { c.Name, c.Phone });
Extension
methods Anonymous Object
types initializers
26. GETTING STARTED WITH
STANDARD QUERY OPERATORS
LINQ Query operators are an extension to the .NET Framework
Class Library.
These are a set of extension methods to perform operations in the
context of LINQ queries.
These operators are at the heart of the LINQ foundation and they
are the real elements that make LINQ possible.
28. THE FOLLOWING IS THE LIST OF STANDARD QUERY
OPERATORS ALONG WITH THEIR CATEGORY:
29.
30. LINQ EXAMPLE - QUERYING AN ARRAY
//Create an array of integers
int[] myarray = new int[] { 49, 28, 20, 15, 25,
23, 24, 10, 7, 34 };
//Create a query for odd numbers
var oddNumbers = from i in myarray where i % 2 == 1 select i;
//Compose the original query to create a query for odd numbers
var sorted = from i in oddNumbers orderby i descending select i;
//Display the results of the query
foreach (int i in oddNumbers)
Console.WriteLine(i);
31. Query translates to method invocation.
Where, Join, OrderBy, Select, GroupBy, …
from c in customers
where c.City == "Hove"
select new { c.Name, c.Phone };
customers
.Where(c => c.City == "Hove")
.Select(c => new { c.Name, c.Phone });
35. Querying non-generic collection
Trying to query an ArrayList using LINQ to Objects directly fails
ArrayList books = GetArrayList();
var query = from book in books where book.PageCount > 150
select new { book.Title, book.Publisher.Name };
Nongeneric collections aren’t a big problem with LINQ once you know the trick.
The trick is to use the Cast operator
Querying an ArrayList is possible thanks to the Cast query operator
ArrayList books = GetArrayList();
var query = from book in books.Cast<Book>()
where book.PageCount > 150
select new { book.Title, book.Publisher.Name };
dataGridView.DataSource = query.ToList();
36. Grouping by multiple criteria
var query1 = from book in SampleData.Books
group book by book.Publisher, book.Subject;
var query2 = from book in SampleData.Books
group book by book.Publisher
group book by book.Subject;
The trick is to use an anonymous type to specify the members on which to perform the
grouping.
var query = from book in SampleData.Books
group book by new { book.Publisher, book.Subject };
37. LINQ ARCHITECTURE
var query = from c in customers where c.City == "Hove" select c.Name;
var query = customers.Where(c => c.City == "Hove").Select(c => c.Name);
Source implements Source implements
IEnumerable<T> IQueryable<T>
System.Linq.Enumerable System.Linq.Queryable
Delegate based Expression tree based
Objects SQL DataSets Others…
39. WHAT IS LINQ TO SQL?
LINQ to SQL is an O/RM (object relational mapping) implementation
that ships in the .NET Framework. Which allows you to model a
relational database using .NET classes.
You can then query the database using LINQ, as well as update/ insert/
delete data from it.
LINQ to SQL fully supports transactions, views, and stored procedures.
It also provides an easy way to integrate data validation and business
logic rules into your data model.
40. THE DATACONTEXT, WHAT IS IT?
DataContext will be created for each LinqToSQL-File we
add to our solution.
The DataContext is the main object through which we
will communicate with our database.
The properties of the DataContext class are the tables
and stored procedures in the database we
modelled/created.
41. DLINQ RUNTIME SUPPORT
from c in db.Customers db.Customers.Add(c1);
where c.City == "London"
select c.CompanyName
Application c2.City = “Seattle";
db.Customers.Remove(c3);
Enumerate Objects SubmitChanges()
LINQ to
SQL
SQL Query Rows DML
or SProc or SProcs
SELECT CompanyName INSERT INTO Customer …
FROM Customer UPDATE Customer …
WHERE City = 'London' DELETE FROM Customer …
45. LINQ TO XML
Large Improvement Over Existing Model
Supports:
Creating XML
Loading & querying XML
Modifying & saving XML
Streaming, Schema, Annotations, Events
46. LINQ TO XML
New XML API implemented in v3.5 assembly
System.Xml.Linq.dll
Namespaces
System.Xml.Linq
System.Xml.Schema
System.Xml.Xpath
Can be used independently of LINQ
47. KEY CLASSES IN SYSTEM.XML.LINQ
System.Xml.Linq is a “DOM like” API
Manipulates an XML tree in memory
Naturally work with both XML documents and fragments
The two key classes in System.Xml.Linq
48. LOADING XML CONTENT
Loading Xml is performed with;
XElement.Load
XDocument.Load
Both support loading from
URI, XmlReader, TextReader
49. MODIFYING XML
XML tree exposed by XElement is modifiable
Modifications through methods such as:
XElement.Add()
XElement.Remove()
XElement.ReplaceWith()
Modified tree can be persisted via
XElement.Save(), XDocument.Save()
Both supporting filename, TextWriter, XmlWriter.
50. CREATING AN XML DOCUMENT
XNamespace ns = "http://example.books.com";
XDocument books = new XDocument(
new XElement(ns + "bookstore",
new XElement(ns + "book",
new XAttribute("ISBN", isbn),
new XElement(ns + "title", "ASP.NET Book"),
new XElement(ns + "author",
new XElement(ns + "first-name", a.FirstName),
new XElement(ns + "last-name", a.LastName)
)
)
)
);
books.Save(@"C:Books.xml");
51. …MEANWHILE IN C#
No XML Literals, But There’s
Something to Close the Gap
“Paste XML as XElement” Add-in
Add XML to Clipboard
Edit -> Past XML as XElement
Included in VS2008 Samples
Help -> Samples