How to: Return Subsets of Element Properties in a Query
Collapse the table of content
Expand the table of content

How to: Return Subsets of Element Properties in a Query (C# Programming Guide)


Use an anonymous type in a query expression when both of these conditions apply:

  • You want to return only some of the properties of each source element.

  • You do not have to store the query results outside the scope of the method in which the query is executed.

If you only want to return one property or field from each source element, then you can just use the dot operator in the select clause. For example, to return only the ID of each student, write the select clause as follows:

select student.ID;

The following example shows how to use an anonymous type to return only a subset of the properties of each source element that matches the specified condition.

private static void QueryByScore()
    // Create the query. var is required because
    // the query produces a sequence of anonymous types.
    var queryHighScores =
        from student in students
        where student.ExamScores[0] > 95
        select new { student.FirstName, student.LastName };

    // Execute the query.
    foreach (var obj in queryHighScores)
        // The anonymous type's properties were not named. Therefore 
        // they have the same names as the Student properties.
        Console.WriteLine(obj.FirstName + ", " + obj.LastName);
/* Output:
Adams, Terry
Fakhouri, Fadi
Garcia, Cesar
Omelchenko, Svetlana
Zabokritski, Eugene

Note that the anonymous type uses the source element's names for its properties if no names are specified. To give new names to the properties in the anonymous type, write the select statement as follows:

select new { First = student.FirstName, Last = student.LastName };

If you try this in the previous example, then the Console.WriteLine statement must also change:

Console.WriteLine(student.First + " " + student.Last);

Compiling the Code

  • To run this code, copy and paste the class into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 of the .NET Framework, and it will have a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually. For more information, see How to: Create a LINQ Project.

© 2015 Microsoft