sagar savsani
sagar savsani

Reputation: 17

How to convert iqueryable<string> to string in linq?

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

Answers (5)

sagar savsani
sagar savsani

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

hackp0int
hackp0int

Reputation: 4169

return objDatabase.FAPARs.FirstOrDefault(f => f.PARTY_CODE.Equals("P003")).PARTY_NAME 

Upvotes: 0

Jon Skeet
Jon Skeet

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:

  • What do you want to happen if the query has no results?
  • What do you want to happen if the query has one result? (I assume this is simple :)
  • What do you want to happen if the query has more than one result?

The set of methods which allow you to determine all of this are:

  • Single - fail if there isn't exactly one result
  • SingleOrDefault - fail if there's more than one result, return null if there are no results
  • First - fail if there are no results, return the first of many
  • FirstOrDefault - return null if there are no results, or the first of many
  • Last - fail if there are no results, return the last of many
  • LastOrDefault - return null if there are no results, or the last of many

In 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

Travis J
Travis J

Reputation: 82267

Try this:

return objDatabase.FAPARs.Where(f => (f.PARTY_CODE == "P003")).Single(f => f.PARTY_NAME);

Upvotes: 0

dan radu
dan radu

Reputation: 2782

Try

return objDatabase.FAPARs .Where(f => (f.PARTY_CODE == "P003")) .Select(f => f.PARTY_NAME).SingleOrDefault();

Upvotes: 1

Related Questions