问题
I do a sql query which returns a string - service name. this is the query:
IQueryable<string> query = from Comp in ServiceGroupdb.ServiceGroupes
where (Comp.GroupID == groupID)
select Comp.Name;
How do i get the string out of the query?
回答1:
LINQ always returns a sequence, so you have to retrieve the item out of it. If you know that you will have only one result, use Single()
to retrieve that item.
var item = (from Comp in ServiceGroupdb.ServiceGroupes
where (Comp.GroupID == groupID)
select Comp.Name).Single();
There are four LINQ methods to retrieve a single item out of a sequence:
Single()
returns the item, throws an exception if there are 0 or more than one item in the sequence.SingleOrDefault()
returns the item, or default value (null
forstring
). Throws if more than one item in the sequence.First()
returns the first item. Throws if there are 0 items in the sequence.FirstOrDefault()
returns the first item, or the default value if there are no items)
回答2:
To get the first element in your query, you can use query.First()
but if there are no elements, that would throw an exception. Instead, you can use query.FirstOrDefault()
which will give you either the first string, or the default value (null
). So for your query this would work:
var myString = (from Comp in ServiceGroupdb.ServiceGroupes
where Comp.GroupID == groupID
select Comp.Name)
.FirstOrDefault();
回答3:
You're almost there.
Just do
IQueryable<string> query = from Comp in ServiceGroupdb.ServiceGroupes where (Comp.GroupID == groupID) select Comp.Name;
// Loop over all the returned strings
foreach(var s in query)
{
Console.WriteLine(s);
}
Or use query.FirstOrDefault()
as mentioned as you'll only get one result.
回答4:
I find the methods'way is prettier and clearer, so here it goes:
string query = ServiceGroupdb.ServiceGroupes
.Where(Comp => Comp.GroupID == groupID)
.Select(Comp => Comp.Name)
.FirstOrDefault();
回答5:
Just do it like this;
var query = from Comp in ServiceGroupdb.ServiceGroupes where (Comp.GroupID == groupID) select Comp.Name;
query will then contain your result.
来源:https://stackoverflow.com/questions/11326468/how-can-i-convert-iqueryablestring-to-string