Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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);
To run this code, copy and paste the class into a C# console application with a using
directive for System.Linq.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Create C# methods that return values - Training
This module covers the return keyword and returning values from methods.
Documentation
A type defined within a class, struct, or interface is called a nested type in C#.
How to initialize objects by using an object initializer - C#
Learn how to use object initializers to initialize type objects in C# without invoking a constructor. Use an object initializer to define an anonymous type.
Object and Collection Initializers - C#
Object initializers in C# assign values to accessible fields or properties of an object at creation after invoking a constructor.