Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I not return {ModuleName = Admin} from the linq query?

Tags:

c#

linq-to-sql

I am trying to get the string value "Admin" from a linq query, but when I do:

string oldModule = dc.Modules
                             .Where(x => x.Id == um.ModuleId)
                             .Select(s => new {s.ModuleName})
                             .FirstOrDefault().ToString();

It returns { ModuleName = Admin } in the oldModule variable instead of just Admin.

like image 752
Xaisoft Avatar asked Jan 23 '26 00:01

Xaisoft


1 Answers

That's because you've introduced an anonymous type into the projection. Try this:

string oldModule = dc.Modules
                     .Where(x => x.Id == um.ModuleId)
                     .Select(s => s.ModuleName)
                     .FirstOrDefault();

I removed the ToString call as well, which would have thrown a NullReferenceException if the Where clause hadn't matched anything.

like image 114
Jon Skeet Avatar answered Jan 24 '26 21:01

Jon Skeet