C
C#2w ago
Faker

✅ Is it possible to override ToString method for Anonymous type in C#? (Not using overriden one)

Hello guys, just wondering if it was possible to use another implementation of the ToString method for anonymous type. I was just using LINQ to perform the following:
C#
var lessons = context.Lessons.Select(lessons => new
{
StudentFirstName = lessons.Student.FirstName,
StudentLastName = lessons.Student.LastName,
StudentEmail = lessons.Student.Email,
InstructorFirstName = lessons.Instructor.FirstName,
InstructorLastName = lessons.Instructor.LastName,
InstructorEmail = lessons.Instructor.Email,
CarTransmission = lessons.Car.Transmission,
LessonDate = lessons.Date
});
C#
var lessons = context.Lessons.Select(lessons => new
{
StudentFirstName = lessons.Student.FirstName,
StudentLastName = lessons.Student.LastName,
StudentEmail = lessons.Student.Email,
InstructorFirstName = lessons.Instructor.FirstName,
InstructorLastName = lessons.Instructor.LastName,
InstructorEmail = lessons.Instructor.Email,
CarTransmission = lessons.Car.Transmission,
LessonDate = lessons.Date
});
When I use a foreach and output each lesson, I have the overriden format of the ToString method. I manage to change part of it using the following:
C#
Console.WriteLine(lesson.ToString().Replace("{","").Replace("}","").TrimStart());
C#
Console.WriteLine(lesson.ToString().Replace("{","").Replace("}","").TrimStart());
But just wanted to know if it's actually possible to change the ToString format again
4 Replies
jcotton42
jcotton422w ago
You cannot.
Faker
FakerOP2w ago
rip, noted, thanks ! The "best" solution would be to create a class of what I want to project?
jcotton42
jcotton422w ago
Yes, a record will be nice and concise.
Faker
FakerOP2w ago
Ok noted, thanks !

Did you find this page helpful?