This document discusses Language Integrated Query (LINQ) in .NET, including LINQ building blocks, sequences, query operators and expressions, query expression trees, and LINQ to Objects. LINQ allows querying over various data sources like collections, databases, and XML documents using a SQL-like syntax. Query expressions are translated into expression trees which provide optimizations. LINQ to Objects refers to using LINQ directly over IEnumerable collections without an intermediate provider.
This document provides an agenda for a LINQ training that covers:
- A brief history of data access technologies leading to LINQ
- An overview of what LINQ is and the C# language enhancements that support it
- Base concepts like LINQ to Objects, deferred and immediate operators
- More advanced concepts like LINQ to Datasets, XML, and SQL
- Examples and questions
This document provides an introduction and overview of LINQ (Language Integrated Query). It discusses that LINQ allows developers to query data from different sources using a SQL-like syntax directly in .NET code. It also summarizes the key LINQ concepts like data sources, query operators, LINQ providers for different data types, and IDE support for LINQ in Visual Studio.
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.
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
The document provides an overview of LINQ (Language Integrated Query), a new feature in C# 3.0. It discusses LINQ's features such as implicit typing, extension methods, lambda expressions, and anonymous types. It also covers why LINQ is useful for querying and manipulating data, objects, and XML in a type-safe manner. Examples are provided of basic LINQ queries, implicitly typed variables, extension methods, lambda expressions, and object initializers.
This document provides an agenda for a LINQ training that covers:
- A brief history of data access technologies leading to LINQ
- An overview of what LINQ is and the C# language enhancements that support it
- Base concepts like LINQ to Objects, deferred and immediate operators
- More advanced concepts like LINQ to Datasets, XML, and SQL
- Examples and questions
This document provides an introduction and overview of LINQ (Language Integrated Query). It discusses that LINQ allows developers to query data from different sources using a SQL-like syntax directly in .NET code. It also summarizes the key LINQ concepts like data sources, query operators, LINQ providers for different data types, and IDE support for LINQ in Visual Studio.
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.
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
The document provides an overview of LINQ (Language Integrated Query), a new feature in C# 3.0. It discusses LINQ's features such as implicit typing, extension methods, lambda expressions, and anonymous types. It also covers why LINQ is useful for querying and manipulating data, objects, and XML in a type-safe manner. Examples are provided of basic LINQ queries, implicitly typed variables, extension methods, lambda expressions, and object initializers.
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();
LINQ (Language Integrated Query) allows querying of data from various sources like objects, XML, SQL databases using a consistent SQL-like syntax. It provides a standardized model for querying different data types and improves performance over traditional methods. The document provides examples of LINQ to Objects, LINQ to XML and LINQ to SQL queries and promises a demo of LINQ to SQL. It concludes by listing references for further reading on LINQ.
This document provides an introduction and overview of LINQ (Language Integrated Query). It defines LINQ as allowing developers to write SQL queries using a simple language like C# without needing to learn SQL. LINQ provides a unified syntax for querying multiple data sources. The document outlines the structure of a LINQ query, shows how to write one, and lists the stages of executing a query. Advantages include a consistent syntax across data sources and syntax highlighting. Examples demonstrate creating a data context class and querying data from a database and objects.
LINQ (Language Integrated Query) allows querying over different data sources using a consistent query syntax and set of standard query operators. It supports querying objects in memory (LINQ to Objects), as well as querying databases, XML documents, and other data sources. LINQ queries are built using query operators like Where, Select, OrderBy, and are executed lazily, only when the results are enumerated.
LINQ (Language Integrated Query) is Microsoft's technology that allows querying of data from various sources using a common language syntax. It provides a uniform programming model to query and manipulate data regardless of data source. LINQ queries can be executed against in-memory collections, databases, XML documents, and other data sources. The document discusses various LINQ concepts such as LINQ query expressions, deferred execution, implicit typing with var, extension methods of the Enumerable class, and LINQ to Objects for querying arrays and generic/non-generic collections.
LINQ to ADO.NET allows querying of datasets and SQL databases using LINQ. It includes LINQ to DataSet for querying datasets, and LINQ to SQL for interacting directly with SQL databases using entity classes and a DataContext. Entity classes map to database tables, and the DataContext translates LINQ queries to SQL and manages communication with the database. Queries can perform CRUD operations and retrieve related data across tables using joins.
Lambda expressions were introduced in Java 8 as a way to write concise code for functional interfaces. They allow passing code as data and reducing boilerplate code. Other Java 8 features include default methods that allow interfaces to have method implementations, and streams that provide a functional way to process collections of data in a declarative way. Parallel streams allow concurrent processing of data. Lambda expressions, default methods, and streams improved Java's support for functional programming.
This document discusses schemas in GraphQL. It explains that a schema defines the types and fields that are available in a GraphQL application. It provides examples of scalar types like String and Int and object types like Person with fields for name, id, age, and student status. It also describes special root types for queries, mutations, and subscriptions that define the entry points for GraphQL operations. Queries are executed against fields defined in the query type. Resolvers associate fields with data fetching logic and will be covered in the next session.
Resolvers are functions that are used to resolve the data defined in a GraphQL schema. Each field in the schema is bound to a resolver function. Resolver functions take four arguments - parent, args, context, and info. The parent argument contains data from the parent field, args contains any arguments passed in the query, context shares data between resolvers, and info contains execution details. Together, resolvers and schemas allow GraphQL to define and retrieve data.
LINQ (Language Integrated Query) allows querying of data from various sources using a consistent set of operations. It utilizes language features like lambda expressions, extension methods, and anonymous types to enable querying of objects, datasets, XML, and other sources. LINQ queries can select, filter, and order data in a manner similar to SQL and return strongly typed results without needing to define custom classes.
LINQ
The acronym LINQ stands for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, databases, XML documents, and many more. It is through a set of extensions, LINQ ably integrates queries in C# and Visual Basic. This tutorial offers a complete insight into LINQ with ample examples and coding. The entire tutorial is divided into various topics with subtopics that a beginner can be able to move gradually to more complex topics of LINQ.
This document provides a brief overview of Java 8 features including functional interfaces, lambda expressions, stream API, and Optional class. It discusses how functional interfaces provide target types for lambda expressions and can have a single abstract method. Lambda expressions allow implementing functional interfaces concisely without anonymous classes. The stream API provides a powerful way to process collections in a declarative way using lambda expressions. The Optional class avoids null pointer exceptions and allows chaining of method calls on objects that may be null.
This document discusses an update language for topic maps based on tolog. The language allows users to insert, delete, merge, and update data in a topic map using concise statements. The update language builds on an existing tolog implementation and provides architectural benefits like enabling a JDBC-like API and easy network access. Some open questions remain around expressiveness, handling missing values, and supporting rules/templates within updates. The language has been implemented and tested but requires documentation and real-world use before being released to users.
This document discusses Language Integrated Query (LINQ) and some of the C# 3.0 enhancements that support LINQ, such as implicitly typed local variables. It also provides an example of using a delegate and generic method to filter an integer array, allowing the filtering algorithm to be specified by the calling application code. The example shows how an application developer can define a filtering method or use an anonymous method to filter the array to return only odd numbers.
GraphQL is a query language for APIs that allows clients to fetch exactly what they need from a data source. Apollo Server is a library that makes it easy to build GraphQL servers with Node.js. It provides features like combining multiple GraphQL schemas into one. GraphQL uses SDL to define the schema and relationship between types of data. Resolvers are responsible for returning data in response to GraphQL operations like queries, mutations, and subscriptions. Scalar types define basic data types in GraphQL like Int, String and ID.
The document discusses Entity Framework (EF) and code first modeling. It describes the role of entities as conceptual models that map to physical databases. It introduces the entity data model (EDM) as a client-side class model mapped to the database via EF conventions. It describes the DbContext class as representing a unit of work and repository pattern to query and save data. DbSet properties are added to expose database tables. Navigation properties allow modeling relationships. Loading strategies like lazy, eager, and explicit loading are discussed. The document shows how to generate a model from an existing database and make modifications via data annotations. It provides examples of CRUD operations using EF and LINQ queries. Finally, it outlines creating an empty code first model by
This document provides an overview of GraphQL, including:
- GraphQL is a query language for APIs created by Facebook in 2012 that allows clients to request specific data fields and embed requests.
- It addresses issues with REST APIs like multiple requests being needed to join data and consumer having to parse responses.
- GraphQL allows consumer-driven queries that return exactly what is asked for in a hierarchical JSON response.
- The document discusses GraphQL queries, mutations, subscriptions, and introspection capabilities. It provides examples of using GraphQL with Watson Work Services and the Darwino implementation.
Microsoft .Net is a technology that allows the creation of web and windows applications with rich user interfaces. It supports multiple programming languages and uses the .Net framework to build and deploy applications. The .Net Framework includes a class library with reusable types that integrate with the common language runtime. It enables common programming tasks like string management, data collection, and database connectivity. ADO.Net provides the core data access components for .Net applications, including the Connection, Command, Data Reader, and Data Adapter objects to access data from sources like SQL Server. Key features of .Net include LINQ for querying different data sources, anonymous types, extension methods, and controls like ListView and DataPager for paging and sorting data.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
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();
LINQ (Language Integrated Query) allows querying of data from various sources like objects, XML, SQL databases using a consistent SQL-like syntax. It provides a standardized model for querying different data types and improves performance over traditional methods. The document provides examples of LINQ to Objects, LINQ to XML and LINQ to SQL queries and promises a demo of LINQ to SQL. It concludes by listing references for further reading on LINQ.
This document provides an introduction and overview of LINQ (Language Integrated Query). It defines LINQ as allowing developers to write SQL queries using a simple language like C# without needing to learn SQL. LINQ provides a unified syntax for querying multiple data sources. The document outlines the structure of a LINQ query, shows how to write one, and lists the stages of executing a query. Advantages include a consistent syntax across data sources and syntax highlighting. Examples demonstrate creating a data context class and querying data from a database and objects.
LINQ (Language Integrated Query) allows querying over different data sources using a consistent query syntax and set of standard query operators. It supports querying objects in memory (LINQ to Objects), as well as querying databases, XML documents, and other data sources. LINQ queries are built using query operators like Where, Select, OrderBy, and are executed lazily, only when the results are enumerated.
LINQ (Language Integrated Query) is Microsoft's technology that allows querying of data from various sources using a common language syntax. It provides a uniform programming model to query and manipulate data regardless of data source. LINQ queries can be executed against in-memory collections, databases, XML documents, and other data sources. The document discusses various LINQ concepts such as LINQ query expressions, deferred execution, implicit typing with var, extension methods of the Enumerable class, and LINQ to Objects for querying arrays and generic/non-generic collections.
LINQ to ADO.NET allows querying of datasets and SQL databases using LINQ. It includes LINQ to DataSet for querying datasets, and LINQ to SQL for interacting directly with SQL databases using entity classes and a DataContext. Entity classes map to database tables, and the DataContext translates LINQ queries to SQL and manages communication with the database. Queries can perform CRUD operations and retrieve related data across tables using joins.
Lambda expressions were introduced in Java 8 as a way to write concise code for functional interfaces. They allow passing code as data and reducing boilerplate code. Other Java 8 features include default methods that allow interfaces to have method implementations, and streams that provide a functional way to process collections of data in a declarative way. Parallel streams allow concurrent processing of data. Lambda expressions, default methods, and streams improved Java's support for functional programming.
This document discusses schemas in GraphQL. It explains that a schema defines the types and fields that are available in a GraphQL application. It provides examples of scalar types like String and Int and object types like Person with fields for name, id, age, and student status. It also describes special root types for queries, mutations, and subscriptions that define the entry points for GraphQL operations. Queries are executed against fields defined in the query type. Resolvers associate fields with data fetching logic and will be covered in the next session.
Resolvers are functions that are used to resolve the data defined in a GraphQL schema. Each field in the schema is bound to a resolver function. Resolver functions take four arguments - parent, args, context, and info. The parent argument contains data from the parent field, args contains any arguments passed in the query, context shares data between resolvers, and info contains execution details. Together, resolvers and schemas allow GraphQL to define and retrieve data.
LINQ (Language Integrated Query) allows querying of data from various sources using a consistent set of operations. It utilizes language features like lambda expressions, extension methods, and anonymous types to enable querying of objects, datasets, XML, and other sources. LINQ queries can select, filter, and order data in a manner similar to SQL and return strongly typed results without needing to define custom classes.
LINQ
The acronym LINQ stands for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, databases, XML documents, and many more. It is through a set of extensions, LINQ ably integrates queries in C# and Visual Basic. This tutorial offers a complete insight into LINQ with ample examples and coding. The entire tutorial is divided into various topics with subtopics that a beginner can be able to move gradually to more complex topics of LINQ.
This document provides a brief overview of Java 8 features including functional interfaces, lambda expressions, stream API, and Optional class. It discusses how functional interfaces provide target types for lambda expressions and can have a single abstract method. Lambda expressions allow implementing functional interfaces concisely without anonymous classes. The stream API provides a powerful way to process collections in a declarative way using lambda expressions. The Optional class avoids null pointer exceptions and allows chaining of method calls on objects that may be null.
This document discusses an update language for topic maps based on tolog. The language allows users to insert, delete, merge, and update data in a topic map using concise statements. The update language builds on an existing tolog implementation and provides architectural benefits like enabling a JDBC-like API and easy network access. Some open questions remain around expressiveness, handling missing values, and supporting rules/templates within updates. The language has been implemented and tested but requires documentation and real-world use before being released to users.
This document discusses Language Integrated Query (LINQ) and some of the C# 3.0 enhancements that support LINQ, such as implicitly typed local variables. It also provides an example of using a delegate and generic method to filter an integer array, allowing the filtering algorithm to be specified by the calling application code. The example shows how an application developer can define a filtering method or use an anonymous method to filter the array to return only odd numbers.
GraphQL is a query language for APIs that allows clients to fetch exactly what they need from a data source. Apollo Server is a library that makes it easy to build GraphQL servers with Node.js. It provides features like combining multiple GraphQL schemas into one. GraphQL uses SDL to define the schema and relationship between types of data. Resolvers are responsible for returning data in response to GraphQL operations like queries, mutations, and subscriptions. Scalar types define basic data types in GraphQL like Int, String and ID.
The document discusses Entity Framework (EF) and code first modeling. It describes the role of entities as conceptual models that map to physical databases. It introduces the entity data model (EDM) as a client-side class model mapped to the database via EF conventions. It describes the DbContext class as representing a unit of work and repository pattern to query and save data. DbSet properties are added to expose database tables. Navigation properties allow modeling relationships. Loading strategies like lazy, eager, and explicit loading are discussed. The document shows how to generate a model from an existing database and make modifications via data annotations. It provides examples of CRUD operations using EF and LINQ queries. Finally, it outlines creating an empty code first model by
This document provides an overview of GraphQL, including:
- GraphQL is a query language for APIs created by Facebook in 2012 that allows clients to request specific data fields and embed requests.
- It addresses issues with REST APIs like multiple requests being needed to join data and consumer having to parse responses.
- GraphQL allows consumer-driven queries that return exactly what is asked for in a hierarchical JSON response.
- The document discusses GraphQL queries, mutations, subscriptions, and introspection capabilities. It provides examples of using GraphQL with Watson Work Services and the Darwino implementation.
Microsoft .Net is a technology that allows the creation of web and windows applications with rich user interfaces. It supports multiple programming languages and uses the .Net framework to build and deploy applications. The .Net Framework includes a class library with reusable types that integrate with the common language runtime. It enables common programming tasks like string management, data collection, and database connectivity. ADO.Net provides the core data access components for .Net applications, including the Connection, Command, Data Reader, and Data Adapter objects to access data from sources like SQL Server. Key features of .Net include LINQ for querying different data sources, anonymous types, extension methods, and controls like ListView and DataPager for paging and sorting data.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
The document discusses Language Integrated Query (LINQ), which introduces a standard query syntax in .NET languages like C# and VB.NET. LINQ allows querying of different data sources like collections, XML documents, and databases. It provides compile-time checking and IntelliSense support. LINQ queries can be reused and reduce code compared to traditional approaches. The document also covers LINQ architecture, advantages, disadvantages, syntax, lambda expressions, and common query operators like filtering, sorting, aggregation, partitioning, and more.
This document discusses LINQ to Relational (L2R) in Visual Studio 2008 SP1. It explains that L2R allows querying and modifying relational databases using LINQ syntax. L2R works with existing ADO.NET providers for SQL Server, Oracle, and other databases. L2R provides commonality for querying and modifying data across different data sources using LINQ, while different providers may take different approaches for modifying data. The key aspects of L2R are translating LINQ queries to SQL, materializing query results as objects, and translating data modifications to the appropriate commands.
Learning to Spot and Refactor Inconsistent Method NamesDongsun Kim
To ensure code readability and facilitate software maintenance, program methods must be named properly. In particular, method names must be consistent with the corresponding method implementations. Debugging method names remains an important topic in the literature, where various approaches analyze commonalities among method names in a large dataset to detect inconsistent method names and suggest better ones. We note that the state-of-the-art does not analyze the implemented code itself to assess consistency. We thus propose a novel automated approach to debugging method names based on the analysis of consistency between method names and method code. The approach leverages deep feature representation techniques adapted to the nature of each artifact. Experimental results on over 2.1 million Java methods show that we can achieve up to 15 percentage points improvement over the state-of-the-art, establishing a record performance of 67.9% F1-measure in identifying inconsistent method names. We further demonstrate that our approach yields up to 25% accuracy in suggesting full names, while the state-of-the-art lags far behind at 1.1% accuracy. Finally, we report on our success in fixing 66 inconsistent method names in a live study on projects in the wild.
.NET is a platform that provides standardized services across any device or operating system. It includes a common language runtime (CLR) that manages code execution and memory. The .NET Framework provides a library of reusable types and classes. Developers can create applications using any .NET-compatible language like C# or VB.NET, and Visual Studio .NET is used for development.
This document discusses reactive programming and introduces some key concepts:
1) Reactive programming fundamentally changes how asynchronous and event-based programming is approached by using interfaces like IObservable and IObserver instead of interfaces like IEnumerable and IEnumerator.
2) LINQ queries can be used with observable collections in a similar way they are used with enumerable collections in interactive programs.
3) The Reactive Framework ported to JavaScript allows easy conversion of existing DOM and XMLHttpRequest code to reactive code in a small download size. It also includes bindings for libraries like jQuery, MooTools, and Dojo.
The document discusses C# and the .NET framework. It covers:
- The goals and components of the .NET framework, including the common language runtime (CLR) and class library.
- Key concepts in .NET like value types, reference types, boxing/unboxing, and the unified type system.
- Features that enable component-oriented development in C# like properties, events, and attributes.
- Productivity features of C# like parameter arrays, ref/out parameters, and foreach loops.
This document discusses LINQ (Language Integrated Query) features in C#, including introducing LINQ to Objects, basic query expressions for projection and selection, and anonymous types. It provides examples of how LINQ to Objects maps to extension methods, functional and declarative expressibility using LINQ, details about the LINQ translation process from query expressions to method calls, and examples of using anonymous types.
This document describes DeepAPI, a deep learning model that uses an RNN encoder-decoder architecture to generate API usage sequences from natural language queries. It trains on a large corpus of code snippets paired with their documentation comments. DeepAPI is shown to outperform traditional IR approaches by better understanding query semantics and word order. Automatic and human evaluations demonstrate its ability to generate accurate and relevant API sequences for a variety of queries. Parameters like hidden units and word dimensions are analyzed. Enhancements like weighting APIs by importance further improve performance. DeepAPI has applications beyond code search like synthesis of sample code from query understanding.
This document provides an overview of ADO.NET Entity Framework (EF), which is an object-relational mapping (ORM) framework that allows .NET developers to work with relational data using domain-specific objects. It discusses key EF concepts like the entity data model, architecture, features, and lifecycle. The document explains that EF maps database tables and relationships to .NET classes and allows LINQ queries over object collections to retrieve and manipulate data, hiding SQL complexity. It also covers the ObjectContext class that manages database connections and entities.
The document discusses new features in .NET 7 including:
1) Static abstract members can now be added to interfaces to allow for generic math and parsing functionality.
2) File scoped types allow types to only exist within the file they are declared.
3) Time related types now support microseconds and nanoseconds for more precision.
4) StringSyntaxAttribute allows marking strings as containing specific types like JSON for validation and syntax highlighting.
The document discusses Entity Framework and LINQ. It defines Entity Framework as an object-relational mapping framework that allows automated data access from domain objects to a relational database. It describes LINQ as a set of features that adds powerful query capabilities to the C# language syntax. The presentation covers Entity Framework architecture and concepts like code first, database first and model first approaches. It also explains LINQ fundamentals like deferred execution, standard query operators, and differences between LINQ and traditional SQL queries.
Visual Studio 2010 and .NET 4 provide new tools for parallel programming including Parallel LINQ (PLINQ) and the Task Parallel Library (TPL). PLINQ allows existing LINQ queries to run in parallel by partitioning and merging data across threads. The TPL simplifies writing multithreaded code through tasks that represent asynchronous and parallel operations. These new frameworks make it easier for developers to write scalable parallel code that takes advantage of multicore processors.
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
Did interfaces in C# need evolution? Maybe yes. Are they violating some fundamental principles? We see. Are we asking for some hoops? Let's see all this by telling a story (of code, of course)
The document provides an overview of the .NET Framework, which is Microsoft's platform for application development. It describes the key components of the .NET Framework architecture, including the Common Language Runtime (CLR) environment that executes managed code, the framework class library, and support for different programming languages. The CLR is similar to a virtual machine that controls execution of .NET code and provides services like memory management and security.
This document discusses LINQ (Language Integrated Query), which is Microsoft's technology for querying data from various sources using a common language. LINQ allows querying data from in-memory collections, databases, XML documents, and other sources. It provides a uniform programming model that is independent of data sources. LINQ queries are executed using deferred execution, where the query is not run until its results are iterated over. The document covers LINQ query expressions, extension methods, implicit typing with LINQ queries, and returning query results.
This document introduces IDAPython, an extension for IDA that brings Python scripting capabilities to aid in binary analysis. It provides examples of using IDAPython to iterate through functions, segments, instructions, calculate cyclomatic complexity, and automate IDA. The examples demonstrate basic usage and provide a starting point for interested individuals. The document also includes a function reference section describing the various IDAPython API functions.
Spark SQL is a module for structured data processing on Spark. It integrates relational processing with Spark's functional programming API and allows SQL queries to be executed over data sources via the Spark execution engine. Spark SQL includes components like a SQL parser, a Catalyst optimizer, and Spark execution engines for queries. It supports HiveQL queries, SQL queries, and APIs in Scala, Java, and Python.
This document discusses and lists various tools useful for web design, including integrated development environments (IDEs), lite coding tools, drawing and slicing tools, browsers, browser tools, and source control tools. It provides examples of specific IDEs like Visual Studio and Dreamweaver. It also lists popular browsers, browser debugging tools, image editing programs, and source control programs commonly used by web designers.
The document provides an overview of HTML 5 and its structure and common elements. It discusses the basic structure of an HTML document which includes the html, head, body and doctype elements. It also covers common text formatting elements, headings, paragraphs, lists and more semantic structural tags introduced in HTML 5 like header, nav, aside and section. The document includes examples and exercises for readers to practice the concepts covered.
The document discusses various HTML elements for tables, forms, and frames. It covers core table elements like <table>, <tr>, <td> and provides examples of simple, complete and nested tables. For forms, it describes common input fields like text, textarea, buttons, checkboxes and selects. It also covers attributes for validation, tabs indexes and more. Finally, it discusses frames which allow splitting content across multiple views but are now discouraged due to accessibility and usability issues.
1) The document introduces CSS (Cascading Style Sheets) and discusses how it is used to separate HTML content from presentation through external style sheets, embedded styles, and inline styles.
2) It covers basic CSS syntax including selectors, declarations, properties, and values. Common text-related properties like font, color, size, and alignment are described.
3) The "cascade" of CSS is explained, with browser, user, and author styles having different levels of precedence based on specificity and importance. This determines which styles will apply when conflicts occur.
The document discusses various CSS properties for styling elements, including borders, overflow, margins and paddings, width and height, and lists. It provides examples and live demos of how to apply each property, such as using border shorthand to set multiple border properties at once, rounding corners with border-radius, and creating a menu-like unordered list with floated list items.
The document discusses CSS layout techniques including positioning, floating, opacity, visibility, and display properties. It provides examples and definitions for each property and concept. Live demos are linked to demonstrate the code examples. The document concludes with homework assignments to create web pages using HTML and external CSS applying the layout techniques covered.
CSS 3 is the most recent iteration of Cascading Style Sheets. It is divided into modules and supports new selectors, properties for animation, transitions, transforms, and flexible box layout. Many CSS 3 features are already supported in modern browsers even though CSS 3 has not been fully approved as a specification.
This document discusses processing and exporting images in Adobe Photoshop. It covers Photoshop toolboxes including tools, layers and groups, history, and type. It also discusses must-know concepts for slicing images like backgrounds, tiles, formats, and feathering. The document provides examples for slicing buttons and creating shadows and menus from image assets. It emphasizes using layers, groups, and the save for web option for exporting optimized images.
This document provides steps for converting a web site design from a PSD image to XHTML and CSS. It discusses identifying sections, choosing a layout type, distinguishing content from style, and testing across browsers. Floating DIVs and tables are recommended over frames. Details like images types, centering content, and vertical alignment are covered. Case studies demonstrate analyzing images to extract text vs images and small design details. Homework assigns recreating sample web page designs using semantic HTML and CSS only.
The document introduces Windows Presentation Foundation (WPF) as a new graphical display system for Windows applications. It discusses key WPF features like vector graphics, rich text, animation, audio/video support, styles/templates, commands, and using XAML for declarative UI definition. XAML separates the user interface definition from business logic code and allows different teams to work on UI and code simultaneously.
The document discusses various layout containers in WPF including panels, tab containers, and sizing properties. It describes the Canvas, StackPanel, DockPanel, WrapPanel, Grid, and UniformGrid panels. The Canvas allows absolute positioning while stacking panels arrange elements in order. Grid and UniformGrid use a table layout. TabControl allows switching between tab pages. Properties like Width, Height, and GridSplitter are discussed for sizing elements. Exercises are provided to create layouts using different containers without overusing Grid.
The document provides an overview of basic WPF controls, including text controls like Label and TextBox, button controls like Button and ToggleButton, list controls like ComboBox and ListView, and other controls like Slider, ProgressBar, ToolTip, and how to create custom UserControls. It includes examples and brief descriptions of each control and discusses properties, events, and how to customize their appearance and behavior.
The document provides an overview of 2D and 3D graphics and animations in WPF (Windows Presentation Foundation). It discusses WPF's drawing model, resolution independence, basic graphics objects like shapes, brushes and pens. It also covers transformations and animation capabilities in WPF. Live demos are provided for concepts like shapes, lines, ellipses, paths and more.
The document discusses data binding in WPF, including:
- Simple binding of control properties to object properties using the Binding syntax
- Using data contexts to set a common data source for multiple controls
- The Binding class and properties like Path, Mode, Converter for more complex bindings
- Value conversion between data types using IValueConverter
- Data validation using ValidationRules to validate property values
- Advanced binding syntax including relative sources and update triggers
The document provides an overview of complex data binding in WPF, including binding to collections, accessing selected items, lookup bindings, data templates, sorting, filtering, grouping, object data providers, relational data binding, and XML data binding. Key points covered include binding list controls, using display and value member paths, collection views for navigation and filtering, and declarative and programmatic approaches to sorting and grouping data.
This document discusses key XAML concepts including dependency properties, trees in XAML/WPF/Silverlight, routing events, and commanding. It defines dependency objects and properties, describes the visual and logical trees, and covers attached properties, custom dependency properties, traversing trees, and implementing commands using interfaces like ICommand and RelayCommand. Live demos are provided for many of these concepts.
This document provides an introduction to the Model-View-ViewModel (MVVM) architectural pattern, which is commonly used in WPF and Silverlight applications. It describes the key components of MVVM - the View, Model, and ViewModel layers. The ViewModel acts as a mediator between the View and Model layers, exposing properties and commands to the View. Changes in the Model are communicated to the View via notification events using the INotifyPropertyChanged interface. The document includes a simple example of implementing MVVM to manage a list of names, and discusses how real-world applications can utilize this pattern.
This document discusses various topics related to connecting WPF applications to databases using LINQ and Entity Framework, including:
- Using Entity Framework's DbContext to access data from a database in the view model
- Implementing master-detail navigation by binding child collections to a selected parent object
- Using a DataPersister class to abstract data access from the view model for testability
- Paging through long lists of data for improved performance
- Examples of building a CRUD interface in WPF to manage hierarchical data like categories and products stored in a database.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Infrastructure Challenges in Scaling RAG with Custom AI modelsZilliz
Building Retrieval-Augmented Generation (RAG) systems with open-source and custom AI models is a complex task. This talk explores the challenges in productionizing RAG systems, including retrieval performance, response synthesis, and evaluation. We’ll discuss how to leverage open-source models like text embeddings, language models, and custom fine-tuned models to enhance RAG performance. Additionally, we’ll cover how BentoML can help orchestrate and scale these AI components efficiently, ensuring seamless deployment and management of RAG systems in the cloud.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
4. LINQ Building BlocksLINQ Building Blocks
Software developers spend a lot of time toSoftware developers spend a lot of time to
obtain and manipulate dataobtain and manipulate data
Data can be stored inData can be stored in
CollectionsCollections
DatabasesDatabases
XML documentsXML documents
etc...etc...
As of .NET 3.5 developers can use LINQ – aAs of .NET 3.5 developers can use LINQ – a
simplified approach to data manipulationsimplified approach to data manipulation
4
5. LINQ Building Blocks (2)LINQ Building Blocks (2)
LINQLINQ is a set of extensions to .NET Frameworkis a set of extensions to .NET Framework
Encompasses language-integrated query, set,Encompasses language-integrated query, set,
and transform operationsand transform operations
Consistent manner to obtain and manipulateConsistent manner to obtain and manipulate
"data" in the broad sense of the term"data" in the broad sense of the term
QueryQuery expressionsexpressions can be defined directlycan be defined directly
within the C# programming languagewithin the C# programming language
Used to interact with numerous data typesUsed to interact with numerous data types
Converter toConverter to expression treesexpression trees at compile timeat compile time
and evaluated at runtimeand evaluated at runtime 5
6. LINQ Building Blocks (3)LINQ Building Blocks (3)
LINQ allows query expressions to manipulate:LINQ allows query expressions to manipulate:
Any object implementingAny object implementing IEnumerable<T>IEnumerable<T>
Collections of objectsCollections of objects
RRelational databaseselational databases
XML documentsXML documents
The query expressions are based on numerousThe query expressions are based on numerous
SQL-likeSQL-like query operatorsquery operators
Intentionally designed to look and feel veryIntentionally designed to look and feel very
similar to SQL expressionssimilar to SQL expressions
6
7. LINQ Building Blocks (4)LINQ Building Blocks (4)
"LINQ" is the term used to describe this"LINQ" is the term used to describe this
overall approach to data accessoverall approach to data access
LINQ to ObjectsLINQ to Objects
LINQ over objects implementingLINQ over objects implementing
IEnumerable<T>IEnumerable<T>
LINQ to SQLLINQ to SQL andand LINQ to EntitiesLINQ to Entities implementimplement
LINQ over relational dataLINQ over relational data
LINQ toLINQ to DataSetDataSet is a superset of LINQ to SQLis a superset of LINQ to SQL
LINQ to XMLLINQ to XML is LINQ over XML documentsis LINQ over XML documents
7
8. LINQ to *LINQ to *
8
LINQ enabled data sourcesLINQ enabled data sources
LINQ toLINQ to
ObjectsObjects
ObjectsObjects
LINQLINQ
to XMLto XML
<book>
<title/>
<author/>
<price/>
</book>
<book>
<title/>
<author/>
<price/>
</book>
XMLXML
LINQ enabled ADO.NET
LINQ toLINQ to
DataSetsDataSets
LINQLINQ
to SQLto SQL
LINQ toLINQ to
EntitiesEntities
Relational DataRelational Data
OthersOthers …C#C# VB.NETVB.NET
.NET Language-Integrated Query (LINQ).NET Language-Integrated Query (LINQ)
9. Query OperationsQuery Operations
All LINQ queryAll LINQ query
operations consist ofoperations consist of
three distinct actions:three distinct actions:
1.1. Obtain the dataObtain the data
sourcesource
2.2. Create the queryCreate the query
3.3. Execute the queryExecute the query
9
11. IEnumerable<T>IEnumerable<T>
andand SequencesSequences
The interfaceThe interface IEnumerable<T>IEnumerable<T> is universalis universal
LINQ data sourceLINQ data source
Implemented by arrays and all .NET genericImplemented by arrays and all .NET generic
collectionscollections
Enables enumerating over a collection ofEnables enumerating over a collection of
elementselements
AA sequencesequence in LINQ means a collectionin LINQ means a collection
implementing theimplementing the IEnumerable<T>IEnumerable<T> interfaceinterface
Any variable declared asAny variable declared as IEnumerable<T>IEnumerable<T> forfor
typetype TT is considered a sequence of typeis considered a sequence of type TT
11
12. IEnumerable<T>IEnumerable<T>
andand SequencesSequences (2)(2)
Most of the Standard Query Operators areMost of the Standard Query Operators are
extension methods in the static classextension methods in the static class
System.Linq.EnumerableSystem.Linq.Enumerable
Prototyped with anPrototyped with an IEnumerable<T>IEnumerable<T> as theiras their
first argumentfirst argument
E.g.E.g. Min(IEnumerable<T>)Min(IEnumerable<T>),,
Where(IEnumerable<T>,Where(IEnumerable<T>, Func<T,Func<T, bool>)bool>)
Use theUse the CastCast oror OfTypeOfType operators to performoperators to perform
LINQ queries on legacy,LINQ queries on legacy, non-genericnon-generic .NET.NET
collectionscollections 12
14. LINQ Query ExpressionsLINQ Query Expressions
When you have a collection of data, a commonWhen you have a collection of data, a common
task is to extract a subset of items based on atask is to extract a subset of items based on a
given requirementgiven requirement
You want to obtain only the items with namesYou want to obtain only the items with names
that contain a numberthat contain a number
Or don’t have embedded spacesOr don’t have embedded spaces
LINQ query expressions can greatly simplifyLINQ query expressions can greatly simplify
the processthe process
Query expressions are written in a declarativeQuery expressions are written in a declarative
query syntax introduced in C# 3.0query syntax introduced in C# 3.0
14
15. LINQ Query Expressions (2)LINQ Query Expressions (2)
LINQLINQ query expressionsquery expressions are written in aare written in a
declarative SQL-like syntaxdeclarative SQL-like syntax
Example: extracting a subset of array containingExample: extracting a subset of array containing
items with names of more than 6 characters:items with names of more than 6 characters:
15
string[] games = {"Morrowind", "BioShock", "Daxter",string[] games = {"Morrowind", "BioShock", "Daxter",
"The Darkness", "Half Life", "System Shock 2"};"The Darkness", "Half Life", "System Shock 2"};
IEnumerable<string> subset =IEnumerable<string> subset =
from g in gamesfrom g in games
where g.Length > 6where g.Length > 6
orderby gorderby g
select g;select g;
foreach (string s in subset)foreach (string s in subset)
Console.WriteLine("Item: {0}", s);Console.WriteLine("Item: {0}", s);
17. LINQ Query Expressions (3)LINQ Query Expressions (3)
In LINQ aIn LINQ a queryquery is a basic languageis a basic language
constructionconstruction
Just like classes, methods and delegates in C#Just like classes, methods and delegates in C#
Query expressions are used to query andQuery expressions are used to query and
transform data from any LINQ-enabled datatransform data from any LINQ-enabled data
sourcesource
A LINQ query is not executed untilA LINQ query is not executed until
You iterate over the query resultsYou iterate over the query results
You try to access any of the elements in theYou try to access any of the elements in the
result setresult set 17
18. QueryQuery OOperatorsperators
Query operatorsQuery operators in C# are keywords like:in C# are keywords like:
fromfrom,, inin,, wherewhere,, orderbyorderby,, selectselect, …, …
For each standard query operator aFor each standard query operator a
corresponding extension method existscorresponding extension method exists
E.g.E.g. wherewhere Where(IEnumerable<T>)Where(IEnumerable<T>)
At compile time the C# compiler translatesAt compile time the C# compiler translates
query expressions into expression treesquery expressions into expression trees
Expression treesExpression trees are sequences of method callsare sequences of method calls
(from(from System.Linq.EnumerableSystem.Linq.Enumerable))
18
19. Query Operators – SyntaxQuery Operators – Syntax
The basic syntax of LINQ queries is:The basic syntax of LINQ queries is:
This selects all elements inThis selects all elements in gamesgames data sourcedata source
You can apply criteria by the operatorYou can apply criteria by the operator wherewhere
Any valid C# boolean expression can be usedAny valid C# boolean expression can be used
19
IEnumerable<string> subset =IEnumerable<string> subset =
from g in games select g;from g in games select g;
IEnumerable<string> subset =IEnumerable<string> subset =
from g in gamesfrom g in games
where g.Price < 20where g.Price < 20
select g;select g;
var subset =var subset =
games.Select(g => g);games.Select(g => g);
var subset =var subset =
games.Select(g => g);games.Select(g => g);
var subset =var subset =
games.Select(g => g).games.Select(g => g).
Where(g => g.Price < 20);Where(g => g.Price < 20);
var subset =var subset =
games.Select(g => g).games.Select(g => g).
Where(g => g.Price < 20);Where(g => g.Price < 20);
20. QueryQuery OOperatorsperators (2)(2)
TTwo sets of LINQ standard operatorswo sets of LINQ standard operators
OOperaperatingting onon IEnumerableIEnumerable<<TT>>
OOperaperatingting onon IQueIQuerryableyable<<TT>>
LINQ query operators are shorthand versionsLINQ query operators are shorthand versions
for various extension methodsfor various extension methods
Defined inDefined in System.Linq.EnumerableSystem.Linq.Enumerable typetype
Example:Example:
20
IEnumerable<string> subset =IEnumerable<string> subset =
games.Where(g => g.Price < 20);games.Where(g => g.Price < 20);
var subset =var subset =
from g in gamesfrom g in games
where g.Price < 20where g.Price < 20
select g;select g;
var subset =var subset =
from g in gamesfrom g in games
where g.Price < 20where g.Price < 20
select g;select g;
21. QueryQuery OOperatorsperators (3)(3)
The standard query operators provide queryThe standard query operators provide query
capabilities includingcapabilities including
Filtering –Filtering – wherewhere
Projection –Projection – selectselect,, selectManyselectMany
Aggregation –Aggregation – SumSum,, MaxMax,, CountCount,, AverageAverage
Sorting –Sorting – orderbyorderby
Grouping –Grouping – groupbygroupby
…… and many moreand many more
21
22. SStandardtandard QQueryuery
OOperatorsperators – Example– Example
22
string[] games = {"Morrowind", "BioShock","Half Life",string[] games = {"Morrowind", "BioShock","Half Life",
"The Darkness","Daxter", "System Shock 2"};"The Darkness","Daxter", "System Shock 2"};
// Build a query expression using extension methods// Build a query expression using extension methods
// granted to the Array via the Enumerable type// granted to the Array via the Enumerable type
var subset = games.Where(game => game.Length > 6).var subset = games.Where(game => game.Length > 6).
OrderBy(game => game).Select(game => game);OrderBy(game => game).Select(game => game);
foreach (var game in subset)foreach (var game in subset)
Console.WriteLine(game);Console.WriteLine(game);
Console.WriteLine();Console.WriteLine();
var subset =var subset =
from g in gamesfrom g in games
where g.Length > 6where g.Length > 6
orderby gorderby g
select g;select g;
var subset =var subset =
from g in gamesfrom g in games
where g.Length > 6where g.Length > 6
orderby gorderby g
select g;select g;
25. Query Expression TreesQuery Expression Trees
A queryA query expression treeexpression tree is an efficient datais an efficient data
structure representing a LINQ expressionstructure representing a LINQ expression
Type of abstract syntax tree used for storingType of abstract syntax tree used for storing
parsed expressions from the source codeparsed expressions from the source code
Lambda expressions often translate into queryLambda expressions often translate into query
expression treesexpression trees
IQueryable<T>IQueryable<T> is interface implemented byis interface implemented by
query providers (e.g. LINQ to SQL, LINQ toquery providers (e.g. LINQ to SQL, LINQ to
XML, LINQ to Entities)XML, LINQ to Entities)
IQueryable<T>IQueryable<T> objects use expression treesobjects use expression trees
25
26. Query Expression Trees (2)Query Expression Trees (2)
LINQ queries can be performed over twoLINQ queries can be performed over two
standard .NET interfaces:standard .NET interfaces:
IEnumerable<T>IEnumerable<T>
At compile time IL is emittedAt compile time IL is emitted
IQueryable<T>IQueryable<T>
At compile time a query expression tree isAt compile time a query expression tree is
emittedemitted
Both are evaluated at runtimeBoth are evaluated at runtime
26
27. Query Expression Trees (3)Query Expression Trees (3)
When any element of theWhen any element of the IQueryable<T>IQueryable<T>
result is being accessed for the first timeresult is being accessed for the first time
A query is generated from the expression treeA query is generated from the expression tree
and is executedand is executed
27
int[] nums = new int[] {int[] nums = new int[] {
6, 2, 7, 1, 9, 3 };6, 2, 7, 1, 9, 3 };
var numsLessThanFour =var numsLessThanFour =
from i in numsfrom i in nums
where i < 4where i < 4
select i;select i;
foreach (var item in numsLessThanFour)foreach (var item in numsLessThanFour)
Console.WriteLine(item);Console.WriteLine(item);
Query isQuery is
generated andgenerated and
executed hereexecuted here
Variable is of typeVariable is of type
IQueryable<intIQueryable<int
>>
28. Expression Trees – BenefitsExpression Trees – Benefits
IQueryable<T>IQueryable<T> uses expression trees whichuses expression trees which
provide it mechanisms:provide it mechanisms:
For smart decisions and optimizations whenFor smart decisions and optimizations when
query is generatedquery is generated
Based on analysis of expression treesBased on analysis of expression trees
Optimizing multiple nested or complex queriesOptimizing multiple nested or complex queries
Combining multiple queries into very efficientCombining multiple queries into very efficient
single onesingle one
28
30. LINQ to ObjectsLINQ to Objects
LINQ to ObjectsLINQ to Objects refers to using LINQ queriesrefers to using LINQ queries
directly overdirectly over IEnumerable<TIEnumerable<T>> collectioncollection
Without the an intermediate LINQ provider orWithout the an intermediate LINQ provider or
API, such as LINQ to SQL or LINQ to XMLAPI, such as LINQ to SQL or LINQ to XML
Applicable to any enumerable collectionApplicable to any enumerable collection
The old school data retrieval approachThe old school data retrieval approach
Write complexWrite complex foreachforeach loops that specify howloops that specify how
to retrieve data from a collectionto retrieve data from a collection
ТТhe LINQ approach – write declarative codehe LINQ approach – write declarative code
that describes what to be retrievedthat describes what to be retrieved 30
31. LINQ to Objects – AdvantagesLINQ to Objects – Advantages
LINQ queries offer three main advantages overLINQ queries offer three main advantages over
traditionaltraditional foreachforeach loopsloops
They are more concise and easy-to-readThey are more concise and easy-to-read
Especially when filtering by multiple conditionsEspecially when filtering by multiple conditions
Provide powerful filtering, ordering, andProvide powerful filtering, ordering, and
grouping capabilitiesgrouping capabilities
Can be ported to other data sources with littleCan be ported to other data sources with little
or no modificationor no modification
31
32. LINQ to Objects – ExampleLINQ to Objects – Example
LINQ to ObjectsLINQ to Objects is performing SQL-like queriesis performing SQL-like queries
on in-memory data collections and arrayson in-memory data collections and arrays
32
string[] presidents = { "Adams", "Arthur", "Buchanan",string[] presidents = { "Adams", "Arthur", "Buchanan",
"Bush", "Carter","Cleveland","Clinton", "Coolidge","Bush", "Carter","Cleveland","Clinton", "Coolidge",
"Eisenhower", "Fillmore", "Ford", "Garfield","Grant","Eisenhower", "Fillmore", "Ford", "Garfield","Grant",
"Harding", "Harrison", "Hayes", "Hoover", "Jackson","Harding", "Harrison", "Hayes", "Hoover", "Jackson",
"Jefferson", "Johnson", "Kennedy", "Lincoln","Jefferson", "Johnson", "Kennedy", "Lincoln",
"Madison", "McKinley", "Monroe", "Nixon", "Pierce","Madison", "McKinley", "Monroe", "Nixon", "Pierce",
"Polk", "Reagan", "Roosevelt", "Taft", "Taylor","Polk", "Reagan", "Roosevelt", "Taft", "Taylor",
"Truman", "Tyler", "Van Buren", "Washington","Truman", "Tyler", "Van Buren", "Washington",
"Wilson"};"Wilson"};
string president =string president =
presidents.Where(p => p.StartsWith("Lin")).First();presidents.Where(p => p.StartsWith("Lin")).First();
Console.WriteLine(president);Console.WriteLine(president);
string president =string president =
(from p in presidents(from p in presidents
where p.StartsWith("Lin")where p.StartsWith("Lin")
select p).First();select p).First();
string president =string president =
(from p in presidents(from p in presidents
where p.StartsWith("Lin")where p.StartsWith("Lin")
select p).First();select p).First();
34. Counting the Occurrences ofCounting the Occurrences of
a Word in a String – Examplea Word in a String – Example
34
string text = "Historically, the world of data …";string text = "Historically, the world of data …";
……
string searchTerm = "data";string searchTerm = "data";
string[] source = text.Split(string[] source = text.Split(
new char[] { '.', '?', '!', ' ', ';', ':', ',' },new char[] { '.', '?', '!', ' ', ';', ':', ',' },
StringSplitOptions.RemoveEmptyEntries);StringSplitOptions.RemoveEmptyEntries);
// Use ToLower() to match both "data" and "Data"// Use ToLower() to match both "data" and "Data"
var matchQuery =var matchQuery =
from word in textfrom word in text
where word.ToLower() == searchTerm.ToLower()where word.ToLower() == searchTerm.ToLower()
select word;select word;
int wordCount =int wordCount =
matchQuery.Count();matchQuery.Count();
int wordCount = text.Select(int wordCount = text.Select(
w => w.toLower() ==w => w.toLower() ==
searchTerm.ToLower()).Count();searchTerm.ToLower()).Count();
int wordCount = text.Select(int wordCount = text.Select(
w => w.toLower() ==w => w.toLower() ==
searchTerm.ToLower()).Count();searchTerm.ToLower()).Count();
35. Count the OccurrencesCount the Occurrences
of a Word in a Stringof a Word in a String
Live DemoLive Demo
37. QueryingQuerying CCollectionsollections
What can we query?What can we query?
Not everything can be queried by LINQ toNot everything can be queried by LINQ to
ObjectsObjects
The objects need to be a collectionThe objects need to be a collection
It must implement theIt must implement the IEnumerable<T>IEnumerable<T>
interfaceinterface
The good newsThe good news
Almost all standard collections in .NETAlmost all standard collections in .NET
Framework implementsFramework implements IEnumerable<T>IEnumerable<T>
37
38. QueryingQuerying CCollectionsollections (2)(2)
What can be queried using LINQ to Objects?What can be queried using LINQ to Objects?
Arrays –Arrays – T[]T[]
Generic lists –Generic lists – List<T>List<T>
Generic dictionaries –Generic dictionaries – Dictionary<K,V>Dictionary<K,V>
Strings –Strings – stringstring
Other collections that implementsOther collections that implements
IEnumerable<T>IEnumerable<T>
38
39. Querying ArraysQuerying Arrays
Any kind of arrays can be used with LINQAny kind of arrays can be used with LINQ
Can be even anCan be even an untypeduntyped array of objectsarray of objects
Queries can be applied to arrays of customQueries can be applied to arrays of custom
objectsobjects
Example:Example:
39
Book[] books = {Book[] books = {
new Book { Title="LINQ in Action" },new Book { Title="LINQ in Action" },
new Book { Title="LINQ for Fun" },new Book { Title="LINQ for Fun" },
new Book { Title="Extreme LINQ" } };new Book { Title="Extreme LINQ" } };
var titles = booksvar titles = books
.Where(book => book.Title.Contains("Action")).Where(book => book.Title.Contains("Action"))
.Select(book => book.Title);.Select(book => book.Title);
var titles =var titles =
from b in booksfrom b in books
where b.Title.Contains("Action")where b.Title.Contains("Action")
select b.Title;select b.Title;
var titles =var titles =
from b in booksfrom b in books
where b.Title.Contains("Action")where b.Title.Contains("Action")
select b.Title;select b.Title;
40. Querying Generic ListsQuerying Generic Lists
The previous example can be adapted to workThe previous example can be adapted to work
with a generic listwith a generic list
List<T>List<T>,, LinkedList<T>LinkedList<T>,, Queue<T>Queue<T>,,
Stack<T>Stack<T>,, HashSet<T>HashSet<T>, etc., etc.
40
List<Book> books = new List<Book>() {List<Book> books = new List<Book>() {
new Book { Title="LINQ in Action" },new Book { Title="LINQ in Action" },
new Book { Title="LINQ for Fun" },new Book { Title="LINQ for Fun" },
new Book { Title="Extreme LINQ" } };new Book { Title="Extreme LINQ" } };
var titles = booksvar titles = books
.Where(book => book.Title.Contains("Action")).Where(book => book.Title.Contains("Action"))
.Select(book => book.Title);.Select(book => book.Title);
42. Querying StringsQuerying Strings
AlthoughAlthough System.StringSystem.String may not bemay not be
perceived as a collection at first sightperceived as a collection at first sight
It actually is a collection, because it implementsIt actually is a collection, because it implements
IEnumerable<char>IEnumerable<char>
String objects can be queried with LINQ toString objects can be queried with LINQ to
Objects, like any other collectionObjects, like any other collection
42
var count = "Non-letter characters in this string: 8"var count = "Non-letter characters in this string: 8"
.Where(c => !Char.IsLetter(c)).Where(c => !Char.IsLetter(c))
.Count();.Count();
Console.WriteLine(count);Console.WriteLine(count);
// The result is: 8// The result is: 8
var count =var count =
(from c in "Non-letter…"(from c in "Non-letter…"
where !Char.IsLetter(c)where !Char.IsLetter(c)
select c).Count();select c).Count();
var count =var count =
(from c in "Non-letter…"(from c in "Non-letter…"
where !Char.IsLetter(c)where !Char.IsLetter(c)
select c).Count();select c).Count();
44. Aggregation OperationsAggregation Operations
An aggregation operation computes a singleAn aggregation operation computes a single
value from a collection of valuesvalue from a collection of values
Example of aggregation of field over aExample of aggregation of field over a
sequence of employeessequence of employees
44
NameName SalarySalary
Bay IvanBay Ivan 12500,0012500,00
Bat RamboBat Rambo 13500,0013500,00
Baba YagaBaba Yaga 43300,0043300,00
Kiro the KingKiro the King 29800,0029800,00
Bay MangalBay Mangal 25000,0025000,00
...... ......
MAX(Salary)MAX(Salary)
125500,00125500,00
45. AAggregationggregation MethodsMethods
Average()Average()
Calculates the average value of a collectionCalculates the average value of a collection
Count()Count()
Counts the elements in a collectionCounts the elements in a collection
Max()Max()
Determines the maximum value in a collectionDetermines the maximum value in a collection
Sum()Sum()
Sums the values in a collectionSums the values in a collection
45
46. Aggregation Methods – ExamplesAggregation Methods – Examples
Count(<condition>)Count(<condition>)
Max()Max()
46
double[] temperatures =double[] temperatures =
{28.0, 19.5, 32.3, 33.6, 26.5, 29.7};{28.0, 19.5, 32.3, 33.6, 26.5, 29.7};
int highTempCount = temperatures.Count(p => p > 30);int highTempCount = temperatures.Count(p => p > 30);
Console.WriteLine(highTempCount);Console.WriteLine(highTempCount);
// The result is: 2// The result is: 2
double[] temperatures =double[] temperatures =
{28.0, 19.5, 32.3, 33.6, 26.5, 29.7};{28.0, 19.5, 32.3, 33.6, 26.5, 29.7};
double maxTemp = temperatures.Max();double maxTemp = temperatures.Max();
Console.WriteLine(maxTemp);Console.WriteLine(maxTemp);
// The result is: 33.6// The result is: 33.6
var highTemp =var highTemp =
(from p in temperatures(from p in temperatures
where p > 30where p > 30
select p).Count();select p).Count();
var highTemp =var highTemp =
(from p in temperatures(from p in temperatures
where p > 30where p > 30
select p).Count();select p).Count();
var highTemp =var highTemp =
(from p in temperatures(from p in temperatures
select p).Max();select p).Max();
var highTemp =var highTemp =
(from p in temperatures(from p in temperatures
select p).Max();select p).Max();
47. ProjectionsProjections
ProjectionProjection refers to the act of transforming therefers to the act of transforming the
elements of a collection into a different typeelements of a collection into a different type
The resulting type isThe resulting type is defineddefined by the developerby the developer
Projection operators in LINQProjection operators in LINQ
SelectSelect – projects single values that are based– projects single values that are based
on a transform functionon a transform function
SelectManySelectMany – projects collections of values into– projects collections of values into
a new collection containing all valuesa new collection containing all values
47
48. Projections – ExamplesProjections – Examples
Select(<transform-function))Select(<transform-function))
48
List<string> words =List<string> words =
new List<string>() { "an", "apple", "a", "day" };new List<string>() { "an", "apple", "a", "day" };
var query =var query =
from word in wordsfrom word in words
select word.Substring(0, 1);select word.Substring(0, 1);
foreach (string s in query)foreach (string s in query)
{{
Console.Write("{0} ",s);Console.Write("{0} ",s);
}}
// The result is: a a a d// The result is: a a a d
var query =var query =
words.Select(w =>words.Select(w =>
w.Substring(0,1));w.Substring(0,1));
var query =var query =
words.Select(w =>words.Select(w =>
w.Substring(0,1));w.Substring(0,1));
49. Projections – Examples (2)Projections – Examples (2)
SelectMany(<multi-value-function>)SelectMany(<multi-value-function>)
49
string[] sentence = new string[] {string[] sentence = new string[] {
"The quick brown","The quick brown",
"fox jumped over","fox jumped over",
"the lazy dog"};"the lazy dog"};
// SelectMany returns nine strings// SelectMany returns nine strings
// (sub-iterates the Select result)// (sub-iterates the Select result)
IEnumerable<string> allWords =IEnumerable<string> allWords =
sentence.SelectMany(segment => segment.Split(' '));sentence.SelectMany(segment => segment.Split(' '));
foreach (var word in allWords)foreach (var word in allWords)
Console.WriteLine(" {0}", word);Console.WriteLine(" {0}", word);
// Result: The quick brown fox jumped over the lazy dog// Result: The quick brown fox jumped over the lazy dog
51. ConversionsConversions
Converting a collection to a different typeConverting a collection to a different type
Can change the type of the collectionCan change the type of the collection
Can change the type of the elementsCan change the type of the elements
Conversion operations in LINQ queries areConversion operations in LINQ queries are
useful in a variety of applicationsuseful in a variety of applications
For example:For example:
Enumerable.AsEnumerable<TSourceEnumerable.AsEnumerable<TSource>>
Enumerable.OfType<(TResult)Enumerable.OfType<(TResult)>>
Enumerable.ToArray(TSource)Enumerable.ToArray(TSource)
51
52. CConversiononversion MMethodsethods
If start with "If start with "AsAs""
Change the static type of the source collectionChange the static type of the source collection
but do not enumerate itbut do not enumerate it
If start with "If start with "ToTo""
Enumerate the source collection and turn eachEnumerate the source collection and turn each
item into the corresponding collection typeitem into the corresponding collection type
52
string[] towns =string[] towns =
{"Sofia", "Plovdiv", "Varna", "Bourgas", "Pleven"};{"Sofia", "Plovdiv", "Varna", "Bourgas", "Pleven"};
List<string> list = towns.List<string> list = towns.ToList()ToList();;
53. SortingSorting
A sorting operation orders the elements of aA sorting operation orders the elements of a
sequence based on one or more attributessequence based on one or more attributes
Standard query operatorStandard query operator
OrderBy(…)OrderBy(…)
OrderByDescending(…)OrderByDescending(…)
ThenBy(…)ThenBy(…) – performs a secondary sort in– performs a secondary sort in
ascending orderascending order
ThenByDescending(…)ThenByDescending(…)
Reverse(…)Reverse(…)
53
54. Sorting – ExampleSorting – Example
54
string[] words = { "Bay Kolio", "Pinokio",string[] words = { "Bay Kolio", "Pinokio",
"Dedo Mraz", "Baba Yaga", "Bay Mangal" };"Dedo Mraz", "Baba Yaga", "Bay Mangal" };
IEnumerable<string> query =IEnumerable<string> query =
from word in wordsfrom word in words
orderby word.Length, word.Substring(0, 1) descendingorderby word.Length, word.Substring(0, 1) descending
select word;select word;
foreach (string str in query)foreach (string str in query)
Console.WriteLine(str);Console.WriteLine(str);
/* The result is:/* The result is:
PinokioPinokio
Dedo MrazDedo Mraz
Bay KolioBay Kolio
Baba YagaBaba Yaga
Bay MangalBay Mangal
*/*/
var query =var query =
words.Select(word => word).words.Select(word => word).
OrderBy(word => word.Length).OrderBy(word => word.Length).
ThenByDescending(ThenByDescending(
word => word.Substring(0, 1));word => word.Substring(0, 1));
var query =var query =
words.Select(word => word).words.Select(word => word).
OrderBy(word => word.Length).OrderBy(word => word.Length).
ThenByDescending(ThenByDescending(
word => word.Substring(0, 1));word => word.Substring(0, 1));
55. GroupingGrouping
Operation of putting data into groupsOperation of putting data into groups
The elements in each group share a commonThe elements in each group share a common
value for some attributevalue for some attribute
ExampleExample
55
56. Creating Groups and MapsCreating Groups and Maps
GroupBy()GroupBy()
Groups elements that share a commonGroups elements that share a common
attribute, calledattribute, called keykey
Each group is represented by a sequence ofEach group is represented by a sequence of
IGrouping(TKey,TElement)IGrouping(TKey,TElement) objectsobjects
ToLookup()ToLookup()
InsertsInserts elements into aelements into a Lookup(TKey,Lookup(TKey,
TElement)TElement) based on a key selector functionbased on a key selector function
Distinct()Distinct()
Returns distinct elements form a collectionReturns distinct elements form a collection 56
57. Group By – ExamplesGroup By – Examples
57
var people = new[] {var people = new[] {
new { Name = "Kiki", Town = "Plovdiv"},new { Name = "Kiki", Town = "Plovdiv"},
new { Name = "Pepi", Town = "Sofia"},new { Name = "Pepi", Town = "Sofia"},
new { Name = "Koko", Town = "Sofia"},new { Name = "Koko", Town = "Sofia"},
new { Name = "Mimi", Town = "Plovdiv"}new { Name = "Mimi", Town = "Plovdiv"}
};};
var peopleByTowns =var peopleByTowns =
from p in peoplefrom p in people
group p by p.Town;group p by p.Town;
foreach (var town in peopleByTowns)foreach (var town in peopleByTowns)
{{
Console.Write("Town {0}: ", town.Key);Console.Write("Town {0}: ", town.Key);
foreach (var person in town)foreach (var person in town)
Console.Write("{0} ", person.Name);Console.Write("{0} ", person.Name);
Console.WriteLine();Console.WriteLine();
}}
var peopleByTowns =var peopleByTowns =
people.GroupBy(t => t.Town);people.GroupBy(t => t.Town);
var peopleByTowns =var peopleByTowns =
people.GroupBy(t => t.Town);people.GroupBy(t => t.Town);
58. Group By – Examples (2)Group By – Examples (2)
58
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups =var numberGroups =
from n in numbersfrom n in numbers
group n by n % 3;group n by n % 3;
foreach (var g in numberGroups)foreach (var g in numberGroups)
{{
Console.Write("Remainder: {0} -> ", g.Key);Console.Write("Remainder: {0} -> ", g.Key);
foreach (var n in g)foreach (var n in g)
Console.Write("{0} ", n);Console.Write("{0} ", n);
Console.WriteLine();Console.WriteLine();
}}
// Remainder: 2 -> 5 8 2// Remainder: 2 -> 5 8 2
// Remainder: 1 -> 4 1 7// Remainder: 1 -> 4 1 7
// Remainder: 0 -> 3 9 6 0// Remainder: 0 -> 3 9 6 0
var numberGroups =var numberGroups =
numbers.GroupBy(n => n % 3);numbers.GroupBy(n => n % 3);
var numberGroups =var numberGroups =
numbers.GroupBy(n => n % 3);numbers.GroupBy(n => n % 3);
59. JoinsJoins
Action of relating or associating one dataAction of relating or associating one data
source object with a second data source objectsource object with a second data source object
The two data source objects are associatedThe two data source objects are associated
through a common value or attributethrough a common value or attribute
59
60. Join MethodsJoin Methods
JoinJoin
Joins two sequences based on key selectorJoins two sequences based on key selector
functionfunction
And extracts the joined pairs of valuesAnd extracts the joined pairs of values
GroupJoinGroupJoin
Joins two sequences based on key selectorJoins two sequences based on key selector
functionsfunctions
And groups the resulting matches for eachAnd groups the resulting matches for each
elementelement
60
61. Joins – ExampleJoins – Example
61
var owners = new[] {var owners = new[] {
new { Name = "Koko", Town = "Plovdiv"},new { Name = "Koko", Town = "Plovdiv"},
new { Name = "Pepi", Town = "Sofia"},new { Name = "Pepi", Town = "Sofia"},
};};
var pets = new[] {var pets = new[] {
new { Name = "Sharo", Owner = owners[0] },new { Name = "Sharo", Owner = owners[0] },
new { Name = "Rex", Owner = owners[1] },new { Name = "Rex", Owner = owners[1] },
new { Name = "Poohy", Owner = owners[0] },new { Name = "Poohy", Owner = owners[0] },
};};
var petsWithOwners =var petsWithOwners =
from o in ownersfrom o in owners
join p in pets on o.Name equals p.Owner.Namejoin p in pets on o.Name equals p.Owner.Name
select new { Owner = o.Name, Pet = p.Name };select new { Owner = o.Name, Pet = p.Name };
foreach (var p in petsWithOwners)foreach (var p in petsWithOwners)
Console.WriteLine("{0} owned by {1}", p.Pet, p.Owner);Console.WriteLine("{0} owned by {1}", p.Pet, p.Owner);
var petsWithOwners = owners.Join(pets,var petsWithOwners = owners.Join(pets,
(o => o.Name), (p => p.Owner.Name),(o => o.Name), (p => p.Owner.Name),
(o, p) => new {o.Name, p.Name });(o, p) => new {o.Name, p.Name });
var petsWithOwners = owners.Join(pets,var petsWithOwners = owners.Join(pets,
(o => o.Name), (p => p.Owner.Name),(o => o.Name), (p => p.Owner.Name),
(o, p) => new {o.Name, p.Name });(o, p) => new {o.Name, p.Name });
63. Nested QueriesNested Queries
The queries can be nestedThe queries can be nested
For example:For example:
Suppose we have collections ofSuppose we have collections of PersonPerson andand
collections ofcollections of RoleRole objectsobjects
We want get all roles for given person (ID = 1)We want get all roles for given person (ID = 1)
63
var query = peoplevar query = people
.Where(p => p.ID == 1).Where(p => p.ID == 1)
.SelectMany(p => roles.SelectMany(p => roles
.Where(r => r.ID == p.RoleID).Where(r => r.ID == p.RoleID)
.Select(r =>.Select(r =>
new { p.FirstName, p.LastName, r.Role }));new { p.FirstName, p.LastName, r.Role }));