C# and LINQ Yuan Yu Microsoft Research Silicon Valley.

Slides:



Advertisements
Similar presentations
Developer Knowledge Sharing Eric Sun Dec, What programming language did you learn in school and since then? Now, its time to refresh …
Advertisements

The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
LINQ to objects. Datenmodell Zugriffsklasse Einfache Abfrage IEnumerable booksList = SampleDataAccess.DBooks.Select(b => b); Select(...) Book => object.
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Deep Dive into LINQ Eran Sharabi.NET Development Team Leader JohnBryce Training
The DryadLINQ Approach to Distributed Data-Parallel Computing
LINQ and Collections An introduction to LINQ and Collections.
Distributed Data-Parallel Computing Using a High-Level Programming Language Yuan Yu Michael Isard Joint work with: Andrew Birrell, Mihai Budiu, Jon Currey,
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
DryadLINQ A System for General-Purpose Distributed Data-Parallel Computing Yuan Yu, Michael Isard, Dennis Fetterly, Mihai Budiu, Úlfar Erlingsson, Pradeep.
DryadLINQ A System for General-Purpose Distributed Data-Parallel Computing Yuan Yu, Michael Isard, Dennis Fetterly, Mihai Budiu, Úlfar Erlingsson, Pradeep.
Dryad / DryadLINQ Slides adapted from those of Yuan Yu and Michael Isard.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Chapter 17 Java SE 8 Lambdas and Streams
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
LINQ, An IntroLINQ, An Intro Florin−Tudor Cristea, Microsoft Student Partner.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Programming clusters with DryadLINQ Mihai Budiu Microsoft Research, Silicon Valley Association of C and C++ Users (ACCU) Mountain View, CA, April 13, 2011.
Getting familiar with LINQ to Objects Florin−Tudor Cristea, Microsoft Student Partner.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Training Kinect Mihai Budiu Microsoft Research, Silicon Valley UCSD CNS 2012 RESEARCH REVIEW February 8, 2012.
Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
MAP-REDUCE ABSTRACTIONS 1. Abstractions On Top Of Hadoop We’ve decomposed some algorithms into a map-reduce “workflow” (series of map-reduce steps) –
Functional Programming in Scheme and Lisp.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises 1 Xiang Lian The University of Texas – Pan American Edinburg,
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Large-scale Machine Learning using DryadLINQ Mihai Budiu Microsoft Research, Silicon Valley Ambient Intelligence: From Sensor Networks to Smart Environments.
Aggregator  Performs aggregate calculations  Components of the Aggregator Transformation Aggregate expression Group by port Sorted Input option Aggregate.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
What is Pig ???. Why Pig ??? MapReduce is difficult to program. It only has two phases. Put the logic at the phase. Too many lines of code even for simple.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Functional Programming
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2016
Some slides adapted from those of Yuan Yu and Michael Isard
Introduction to LINQ and Generic Collections
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2013
Intro to LINQ Part 2 – Concepts and LINQ to Objects
MIS Professor Sandvig MIS 324 Professor Sandvig
6.001 SICP Data abstractions
Streams.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Introduction to LINQ Chapter 11.
Chapter 4 Summary Query.
STL - Algorithms.
Distributed System Gang Wu Spring,2018.
MIS Professor Sandvig MIS 324 Professor Sandvig
INFO 344 Web Tools And Development
LINQ - 2 Ravi Kumar C++/C# Team.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises UTPA – Fall 2012 This set of slides is revised from lecture.
LINQ to SQL Part 3.
Advanced .NET Programming I 7th Lecture
CS4540 Special Topics in Web Development LINQ to Objects
Presentation transcript:

C# and LINQ Yuan Yu Microsoft Research Silicon Valley

Collections and Iterators 2 IEnumerable Elements of type T Iterator (current element) Very easy to use: foreach (string name in persons) { Console.WriteLine(name); }

More on IEnumerable IEnumerable is a generic collection – C# generics is very similar to C++ template – T is a type parameter representing its element type IEnumerable.NET collections implement IEnumerable – T[], List, HashSet, Stack, Queue, Dictionary, …

IEnumerable Examples Example 1 Example 2 int[] numbers = { 1, 5, 2, 12, 4, 5 }; int sum = 0; foreach (int x in numbers) { sum += x; } string[] persons = { “Frank”, “Bob”, “Chandu”, “Mike”, “Dennis” } foreach (string name in persons) { Console.WriteLine(name); }

5 LINQ: Operators on Collection Collection collection; bool IsLegal(Key); string Hash(Key); var results = from c in collection where IsLegal(c.key) select new { Hash(c.key), c.value};

LINQ Operators 6 Where (filter) Select (map) GroupBy OrderBy (sort) Aggregate (fold) Join Input

Lambda Expression A nice way to represent anonymous functions Examples: – Func inc = x => x + 1; – Func sqrt = x => Math.Sqrt(x); – Func mul = (x, y) => x * y; Func represents any method that takes a argument of type T and returns a value of type R – Similar to C++ function pointer

Where Filters the elements in a collection based on a predicate Example: IEnumerable Where (IEnumerable source, Func pred) int[] a = { 1, 5, 2, 12, 4, 5 }; IEnumerable result = a.Where(x => x > 4);

Select Transforms each element of a collection into a new form Example: IEnumerable Select (IEnumerable source, Func selector) int[] a = { 1, 5, 2, 12, 4, 5 }; IEnumerable result = a.Select(x => x * x);

Composing Operators Composing computations Or simply You can use “var” to represent the type int[] a = { 1, 5, 2, 12, 4, 5 }; IEnumerable r1 = a.Where(x => x > 4); IEnumerable r2 = r1.Select(x => x *x); int[] a = { 1, 5, 2, 12, 4, 5 }; IEnumerable r2 = a.Where(x => x > 4).Select(x => x * x); int[] a = { 1, 5, 2, 12, 4, 5 }; var r2 = a.Where(x => x > 4).Select(x => x * x);

Query Comprehension If you really hate lambda expression, you can also use the alternate SQL-like syntax int[] a = { 1, 5, 2, 12, 4, 5 }; var r2 = from x in a where x > 4 select x * x;

Invoking User-Defined Functions int[] a = { 1, 5, 2, 12, 4, 5 }; var r2 = from x in a where MyPredicate(x) select Math.Sqrt(x); public static bool MyPredicate(int x) { // User code here }

SelectMany Tranforms each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence IEnumerable Example: IEnumerable SelectMany ( IEnumerable source, Func > selector) string[] lines= { “A line of words of wisdom”, “Dryad and DryadLINQ are great”}; var result = lines.SelectMany(x => x.Split(' '));

OrderBy Sorts the elements of a sequence in ascending order according to a key Example: IEnumerable OrderBy (IEnumerable source, Func keySelector) IEnumerable employees; var result = employees.OrderBy(x => x.Name);

GroupBy Groups the elements of a sequence according to a specified key selector function IGrouping represents a group of elements of type T with key K – g.Key returns the key of the group – g is IEnumerable IEnumerable > GroupBy (IEnumerable source, Func keySelector)

GroupBy Examples Example 1: Example 2: string[] items= { "carrots", "cabbage", "broccoli", "beans", "barley" }; IEnumerable > foodGroups = items.GroupBy(x => x[0]); int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var groups = numbers.GroupBy(x => x % 5);

Distinct Returns distinct elements from a sequence Example IEnumerable Distinct (IEnumerable source) int[] numbers = { 1, 5, 2, 11, 5, 30, 2, 2, 7 }; var result = numbers.Distinct();

Aggregate Applies an accumulator function over a sequence Example: R Aggregate (IEnumerable source, R seed, Func func) double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; double result = doubles.Aggregate(1.0, (r, n) => r * n);

Pre-defined Aggregators Useful pre-defineds – Count, LongCount, Sum, Max, Min, Average, All, Any, Contains, … Examples: IEnumerable numbers; long result = numbers.LongCount();

Exercises (1) Keep all numbers divisible by 5 var div = x.Where(v => v % 5 == 0); The average value var avg = x.Sum() / x.Count(); Normalize the numbers to have a mean value of 0 var avg = x.Sum() / x.Count(); var norm = x.Select(v => v - avg); Keep each number only once var uniq = x.GroupBy(v => v).Select(g => g.Key); var uniq = x.Distinct(); 20

Exercises (2) Flatten lists var flatten = x.SelectMany(v => v); The average of all even #s and of all odd #s var avgs = x.GroupBy(v => v % 2).Select(g => g.Sum() / g.Count()); The most frequent value var freq = x.GroupBy(v => v).OrderBy(g => g.Count()).Select(g => g.Key).First() The number of distinct positive values var pos = x.Where(v => v >= 0).Distinct().Count(); 21

Putting them together: Histogram 22 public static IEnumerable Histogram( IEnumerable input, int k) { var words = input.SelectMany(x => x.line.Split(' ')); var groups = words.GroupBy(x => x); var counts = groups.Select(x => new Pair(x.Key, x.Count())); var ordered = counts.OrderByDescending(x => x.count); var top = ordered.Take(k); return top; } “A line of words of wisdom” [“A”, “line”, “of”, “words”, “of”, “wisdom”] [[“A”], [“line”], [“of”, “of”], [“words”], [“wisdom”]] [ {“A”, 1}, {“line”, 1}, {“of”, 2}, {“words”, 1}, {“wisdom”, 1}] [{“of”, 2}, {“A”, 1}, {“line”, 1}, {“words”, 1}, {“wisdom”, 1}] [{“of”, 2}, {“A”, 1}, {“line”, 1}]

MapReduce in LINQ 23 public static IEnumerable MapReduce ( IEnumerable input, Func > mapper, Func keySelector, Func, IEnumerable > reducer) { var map = input.SelectMany(mapper); var group = map.GroupBy(keySelector); var result = group.SelectMany(reducer); return result; }