Reputation: 17
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);
Upvotes: 0
Views: 4856
Reputation: 17
return objDatabase.FAPARs.OfType<FAPAR>()
.Where(f => (f.PARTY_CODE == PartyCode && f.COMP_NO == ComCode))
.Select(f => f.PARTY_NAME).SingleOrDefault();
Upvotes: 0
Reputation: 4169
return objDatabase.FAPARs.FirstOrDefault(f => f.PARTY_CODE.Equals("P003")).PARTY_NAME
Upvotes: 0
Reputation: 1500225
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 Single
is probably appropriate. If you're querying by an ID which may not exist, then use SingleOrDefault
and check whether the return value is null. If you're not querying by an ID, you probably want to use FirstOrDefault
or just iterate over the results.
(Note that the default value being null
is 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 an IQueryable<int>
, the default returned would be 0.)
Upvotes: 5
Reputation: 82267
Try this:
return objDatabase.FAPARs.Where(f => (f.PARTY_CODE == "P003")).Single(f => f.PARTY_NAME);
Upvotes: 0
Reputation: 2782
Try
return objDatabase.FAPARs .Where(f => (f.PARTY_CODE == "P003")) .Select(f => f.PARTY_NAME).SingleOrDefault();
Upvotes: 1