linq
  1. linq-creating-anonymous-types

Creating Anonymous Types in LINQ

In LINQ, Anonymous Types allow us to create an object without defining its structure. An Anonymous Type is a read-only, immutable type, which is generated by the compiler from a projection in a query expression. Anonymous Types are used to hold temporary data and are not intended to store data long-term.

Syntax

var anonymousObject = new { Property1 = "Value1", Property2 = "Value2" };

Example

Let's create an example of an Anonymous Type in LINQ. We are going to filter some values in a list of students.

var students = new List<Student> {
    new Student { Name = "Alice", Age = 20, Course= "Computer Science" },
    new Student { Name = "Bob", Age = 25, Course= "Mathematics" },
    new Student { Name = "Charlie", Age = 22, Course= "Computer Science" },
};

var selectedStudents = from student in students
                       where student.Course == "Computer Science"
                       select new { student.Name, student.Age };
foreach (var student in selectedStudents) {
    Console.WriteLine($"Name: {student.Name}, Age: {student.Age}");
}

In the above example, we're creating an anonymous type with two properties, Name and Age, by using the select new { } clause in the LINQ query. The selectedStudents variable contains a list of anonymous types that contain only the Name and Age properties of the selected students who are studying computer science.

Output

After running the above code, the output will be:

Name: Alice, Age: 20
Name: Charlie, Age: 22

Explanation

In the above syntax, we use the new { } operator to create an anonymous object with one or more properties. The properties are defined in a comma-separated list of name-value pairs. The compiler infers the types of the properties from the values.

In the example above, we create an anonymous type in the select clause of the LINQ query. We select only the Name and Age properties of students studying Computer Science, resulting in a list of anonymous types.

Use

Anonymous Types are used in LINQ to create a temporary object with selected or transformed data. A typical use case is for data projection or for holding data while it is transformed. Anonymous Types are also used to simplify code by avoiding the need to declare a class with properties explicitly.

Important Points

  • Anonymous Types are read-only and immutable
  • Anonymous Types properties are strongly typed and inferred by the compiler based on the data assigned to them.
  • Anonymous Types are not intended for long term storage, but they are used primarily for transformations.

Summary

In this tutorial, we learned about Anonymous Types in LINQ. We've seen how to create Anonymous Types, their syntax, and how they can be used to hold temporary data. We also demonstrated the use of Anonymous Types in a LINQ query, where Anonymous Types can be used to select specific data from a collection.

Published on: