i have the following code snippet.
in which i just want to return PartyName as a string.
but i get the error:”Cannot implicity convert type ‘System.Linq.Iqueryable to string”
if i want to return only string then what to do?
please help me.
return objDatabase.FAPARs
.Where(f => (f.PARTY_CODE == "P003"))
.Select(f => f.PARTY_NAME);
An
IQueryable<string>represents a query which could return any number of strings. You want one string – so you need to decide what to do in various situations:The set of methods which allow you to determine all of this are:
Single– fail if there isn’t exactly one resultSingleOrDefault– fail if there’s more than one result, return null if there are no resultsFirst– fail if there are no results, return the first of manyFirstOrDefault– return null if there are no results, or the first of manyLast– fail if there are no results, return the last of manyLastOrDefault– return null if there are no results, or the last of manyIn each case, “fail” means “throw an exception”. (IIRC it’s always
InvalidOperationException, at least in LINQ to Objects, but I could be wrong.)So if you’re querying by an ID which must exist (i.e. it’s a bug if it doesn’t) then
Singleis probably appropriate. If you’re querying by an ID which may not exist, then useSingleOrDefaultand check whether the return value is null. If you’re not querying by an ID, you probably want to useFirstOrDefaultor just iterate over the results.(Note that the default value being
nullis due to this being a query returning strings, and string being a reference type. In general it’s the default value of the element type – so if you had anIQueryable<int>, the default returned would be 0.)