How do I not return {ModuleName = Admin} from the linq query?
I am trying to get the string v开发者_StackOverflow社区alue "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.
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.
string oldModule = dc.Modules
.Where(x => x.Id == um.ModuleId)
.Select(s => s.ModuleName)
.FirstOrDefault().ToString();
What about just selecting the ModuleName
property?
(from m in dc.Modules
where m.Id == um.ModuleId
select m.ModuleName).FirstOrDefault()
This happens because new {...} creates a new anonymous type in Select. When you call ToString(), you call it on this anonoymous type, not the ModuleName string. If you just write .Select(s=>s.ModuleName) you will get back a string instead of the anonymous type and oldModule will contain Admin.
In fact, you don't even need ToString() at the end of the query, as the result of FirstOrDefault() is already a string.
What is the new doing in
.Select(s => new {s.ModuleName})
I don't know what you're issue is, but I wouldn't be surprised if that's part of it..
I would also maybe just do .Single(s => s.ModuleName) instead of .select and .firstordefault.
精彩评论