Beruflich Dokumente
Kultur Dokumente
http://msdn.microsoft.com/en-us/library/bb397900
Prerequisites
This walkthrough requires Visual Studio 2010. For a video version of this topic, see Video How to: Writing Queries in C# (LINQ).
Create a C# Project
To create a C# project that targets version 3.5 of the .NET Framework
1. Start Visual Studio. 2. On the File menu, point to New, and then click Project. 3. The upper-right corner of the New Project dialog box has three icons. Click the left icon and make sure that .NET Framework Version 3.5 is checked. 4. Click the Console Application icon under Visual Studio Installed Templates. 5. Give your application a new name, or accept the default name, and click OK. 6. Notice that your project has a reference to System.Core.dll and a using directive for the System.Linq namespace.
1 of 8
5/25/2012 11:39 AM
Walkthrough: Writing Queries in C# (LINQ) public class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Scores; }
http://msdn.microsoft.com/en-us/library/bb397900
// Create a data source by using a collection initializer. static List<Student> students = new List<Student> { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, new Student {First="Claire", Last="ODonnell", ID=112, Scores= new List<int> {75, 84, 91, 39} new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}}, new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}}, new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}}, new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}}, new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}}, new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}}, new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}}, new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}}, new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 6 new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} } };
// Create the query. // The first line could also be written as "var studentQuery =" IEnumerable<Student> studentQuery = from student in students where student.Scores[0] > 90 select student;
2 of 8
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/bb397900
// Execute the query. // var could be used here also. foreach (Student student in studentQuery) { Console.WriteLine("{0}, {1}", student.Last, student.First); }
where student.Scores[0] > 90 && student.Scores[3] < 80 For more information, see where clause (C# Reference).
3 of 8
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/bb397900
2. Now change the orderby clause so that it orders the results in reverse order according to the score on the first test, from the highest score to the lowest score.
orderby student.Scores[0] descending 3. Change the WriteLine format string so that you can see the scores:
Console.WriteLine("{0}, {1} {2}", student.Last, student.First, student.Scores[0]); For more information, see orderby clause (C# Reference).
// studentQuery2 is an IEnumerable<IGrouping<char, Student>> var studentQuery2 = from student in students group student by student.Last[0];
2. Note that the type of the query has now changed. It now produces a sequence of groups that have a char type as a key, and a sequence of Student objects. Because the type of the query has changed, the following code changes the foreach execution loop also:
// studentGroup is a IGrouping<char, Student> foreach (var studentGroup in studentQuery2) { Console.WriteLine(studentGroup.Key); foreach (Student student in studentGroup) { Console.WriteLine(" {0}, {1}", student.Last, student.First); } }
3. Press Ctrl + F5 to run the application and view the results in the Console window. For more information, see group clause (C# Reference).
4 of 8
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/bb397900
Explicitly coding IEnumerables of IGroupings can quickly become tedious. You can write the same query and foreach loop much more conveniently by using var. The var keyword does not change the types of your objects; it just instructs the compiler to infer the types. Change the type of studentQuery and the iteration variable group to var and rerun the query. Note that in the inner foreach loop, the iteration variable is still typed as Student, and the query works just as before. Change the s iteration variable to var and run the query again. You see that you get exactly the same results.
var studentQuery3 = from student in students group student by student.Last[0]; foreach (var groupOfStudents in studentQuery3) { Console.WriteLine(groupOfStudents.Key); foreach (var student in groupOfStudents) { Console.WriteLine(" {0}, {1}", student.Last, student.First); } }
For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).
var studentQuery4 = from student in students group student by student.Last[0] into studentGroup orderby studentGroup.Key select studentGroup; foreach (var groupOfStudents in studentQuery4) { Console.WriteLine(groupOfStudents.Key); foreach (var student in groupOfStudents) { Console.WriteLine(" {0}, {1}", student.Last, student.First); } }
5 of 8
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/bb397900
When you run this query, you will see the groups are now sorted in alphabetical order.
// studentQuery5 is an IEnumerable<string> // This query returns those students whose // first test score was higher than their // average score. var studentQuery5 = from student in students let totalScore = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] where totalScore / 4 < student.Scores[0] select student.Last + " " + student.First; foreach (string s in studentQuery5) { Console.WriteLine(s); }
var studentQuery6 = from student in students let totalScore = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] select totalScore; double averageScore = studentQuery6.Average(); Console.WriteLine("Class average score = {0}", averageScore);
6 of 8
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/bb397900
in the source sequences. Delete or comment out your previous query and execution loop, and replace it with the following code. Note that the query returns a sequence of strings (not Students), and this fact is reflected in the foreach loop.
IEnumerable<string> studentQuery7 = from student in students where student.Last == "Garcia" select student.First; Console.WriteLine("The Garcias in the class are:"); foreach (string s in studentQuery7) { Console.WriteLine(s); }
2. Code earlier in this walkthrough indicated that the average class score is approximately 334. To produce a sequence of Students whose total score is greater than the class average, together with their Student ID, you can use an anonymous type in the select statement:
var studentQuery8 = from student in students let x = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] where x > averageScore select new { id = student.ID, score = x }; foreach (var item in studentQuery8) { Console.WriteLine("Student ID: {0}, Score: {1}", item.id, item.score); }
Next Steps
After you are familiar with the basic aspects of working with queries in C#, you are ready to read the documentation and samples for the specific type of LINQ provider you are interested in: LINQ to SQL LINQ to DataSet LINQ to XML LINQ to Objects
See Also
Tasks
7 of 8
5/25/2012 11:39 AM
Walkthrough: Writing Queries in C# (LINQ) Walkthrough: Writing Queries in Visual Basic Concepts LINQ Query Expressions (C# Programming Guide) Supplementary LINQ Resources Other Resources LINQ (Language-Integrated Query) Getting Started with LINQ in C#
http://msdn.microsoft.com/en-us/library/bb397900
Yes
No
Community Content
2012 Microsoft. All rights reserved.
8 of 8
5/25/2012 11:39 AM