Lecture 09 - LINQ to Objects
Lecture 09 - LINQ to Objects
6 Framework
using System;
namespace MyExtensions
{
class MainClass
{
public static void Main(string[] args)
{
//Since everything extends System.Object, all classes and structures can use this
int myInt = 12345678;
myInt.DisplayDefiningAssembly();
}
}
}
Anonymous Types
• Anonymous types feature
– To quickly model the "shape" of data
– Is based on a supplied set of name-value pairs
– To allow the compiler to generate a new class definition at compile
time
• To define an anonymous type
– Declare an implicitly typed variable
– Specify the data's shape using object initialization syntax
• LINQ makes frequent use of anonymous types
– To project new forms of data on the fly
• Example
– Assume you have a collection of Person objects
– LINQ to obtain information on the age and SSN of each
– LINQ allows compiler to generate a new anonymous type for this info
Anonymous Types
using System;
namespace AnonymousTypes
{
class MainClass
{
public static void Main(string[] args)
{
var purchaseItem = new
{
TimeBought = DateTime.Now,
ItemBought = new { Color = "Red", Make = "Saab", CurrentSpeed = 55 }
};
var ItemBought = purchaseItem.ItemBought;
Console.WriteLine("Color: {0}, Make: {1}, CurrentSpeed: {2}, Bought at: {3}",
ItemBought.Color, ItemBought.Make, ItemBought.CurrentSpeed, purchaseItem.TimeBought);
}
}
}
Roles of LINQ
• The LINQ
– Provides a consistent, symmetrical manner to obtain and manipulate
"data”
– The data can come from different sources
– Can be used to create query expressions
– These are based on numerous query operators designed to look and
feel similar (but not quite identical) to a SQL expression
• LINQ terminologies:
– LINQ to Objects: applying LINQ queries to arrays and collections
– LINQ to XML: using LINQ to manipulate and query XML documents
– LINQ to DataSet: applying LINQ queries to ADO.NET DataSet objects
– LINQ to Entities: using queries within the ADO.NET Entity Framework
– Parallel LINQ (aka PLINQ): Parallel processing of data returned from
LINQ
LINQ Expressions Are Strongly Typed
• It is also important to point out that a LINQ
query expression is strongly typed
– Therefore, the C# compiler will keep you honest
and make sure that these expressions are
syntactically well-formed.
– Tools such as Visual Studio can use metadata for
useful features such as IntelliSense,
autocompletion, and so forth.
APPLYING LINQ QUERIES TO
PRIMITIVE ARRAYS
First LINQ to Array Query
using System;
using System.Linq;
using System.Collections.Generic;
namespace LinqOverArray
{
class MainClass
{
public static void QueryOverStrings()
{
// Assume we have an array of strings.
string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"};
// Build a query expression to find the items in the array that have an embedded space. Then order the result
IEnumerable<string> subset = from g in currentVideoGames
where g.Contains(" ")
orderby g
select g;
// Print out the results.
foreach (string s in subset)
Console.WriteLine("Item: {0}", s);
}
public static void Main(string[] args)
{
Console.WriteLine("************** Fun with LINQ **************");
QueryOverStrings();
Console.ReadLine();
}
}
}
Once Again, Without LINQ
using System;
using System.Collections.Generic;
namespace LinqOverArray
{
class MainClass
{
static void QueryOverStringsLongHand()
{
// Assume we have an array of strings.
string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"};
var carDiff = (from c in myCars select c) Difference with Except extension method
.Except(from c2 in yourCars select c2);
// Get the union of these containers. Union with Union() extension method
var carUnion = (from c in myCars select c)
.Union(from c2 in yourCars select c2);
Console.WriteLine("Here is everything:");
foreach (string s in carUnion)
Console.WriteLine(s); // Prints all common members.
}
Concatenation
static void DisplayConcat()
{
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
var carConcat = (from c in myCars select c) Remove duplicates with Distinct() extension
.Concat(from c2 in yourCars select c2); method
// Prints:
// Yugo Aztec BMW Saab Aztec.
foreach (string s in carConcat.Distinct())
Console.WriteLine(s);
}
LINQ Aggregation Operations
static void AggregateOps()
{
double[] winterTemps = { 2.0, -21.3, 8, -4, 0, 8.2 };