How do I cast IQueryable<System.Guid> to a string?
I have the follo开发者_运维问答wing Linq query and I need to get the Guid result back as a string. The following actually gives me the string representation of the object, "IQueryable". How do I go about getting the guid as a string?
Thanks!
context.ApplicationId =
DataBaseEntities.Applications.Where(a => a.Name == applicationName)
.Select(a => a.Id).ToString();
I suspect you're actually trying to get out a single result so what you'd need is
context.ApplicationId = DataBaseEntities.Applications
.Single(a => a.Name == applicationName).Id.ToString();
Now if your data layer doesn't understand Single
, you could try
context.ApplicationId = DataBaseEntities.Applications
.First(a => a.Name == applicationName).Id.ToString();
Well the sequence can have multiple Guids in... how do you want to join them together? For example, you could just use string.Join
(in .NET 4; .NET 3.5 is slightly trickier):
string guids = DataBaseEntities.Applications
.Where(a => a.Name == applicationName)
.Select(a => a.Id);
string guid = string.Join(',', guids);
Or if you know there will be exactly one match, you could use Single
to get one value, then find the Id, then call ToString
:
string guid = DataBaseEntities.Applications
.Single(a => a.Name == applicationName)
.Id.ToString();
If there could be multiple matches, or none, you need to think about options like FirstOrDefault()
.
An IQueryable
has many results. You can use .Single().ToString();
to ensure there's only one result, then convert that to a string
.
The queryable represents a sequence of Guid
but it seems like you just want one. So either use First
or Single
:
context.ApplicationId = DataBaseEntities.Applications
.Where(a => a.Name == applicationName)
.Select(a => a.Id)
.First()
.ToString();
context.ApplicationId =
DataBaseEntities
.Applications
.Where(a => a.Name == applicationName)
.Select(a => a.Id).
.SingleOrDefault().
.ToString();
First, your select statement is returning a list of Guid's not single Guid. If you really just want one, you should call one of this methods: - First(): if you you might have several, this will take the first one, and throw an error if you there are none - FirstOrDefault(): if you might have several or none, this will take the first one, or default to an empty Guid if there is none - Single(): if there will be exactly one, this will take that one, and will throw an exception if there are none or more than one - SingleOrDefault(): if there will be zero or one, this will take that one, or default to an empty Guid if there is none, or will throw an exception if there are several.
context.ApplicationId =
DataBaseEntities.Applications.Where(a => a.Name == applicationName)
.Select(a => a.Id).Single().ToString();
精彩评论