Linq to return string

40,786

Solution 1

You are getting an IQueryable<String> back from you query. You need either the First or Single or something:

string vend = (from vnd in db.Vendors
         where vnd.VendorID == id
         select vnd.VendorName).First().ToString();

The ToString is not need if VendorName is a String.

string vend = db.Vendors.Single(vnd => vnd.VendorID == id); // more terse 

First will grab the first record from the set and will throw an exception if the set is empty.

FirstOrDefault will return the first record or the default for the type expected, no exception.

Single will return the first record of the set, but will throw an exception if there is more than one record in the set or if the set is empty.

SingleOrDefault will return the first record of the set or the default for the type if empty, but will throw an exception if there are more than one record in the set.

Solution 2

You are calling ToString() on the query itself, not on the result of your query. Try

string vend = (from vnd in db.Vendors
where vnd.VendorID == id
select vnd.VendorName).First();

This gets the first result of the query, which should already be a string (assuming VendorName is a string). Thus, no need to call ToString().

Share:
40,786
Nate Pet
Author by

Nate Pet

Updated on July 09, 2022

Comments

  • Nate Pet
    Nate Pet almost 2 years

    I am not sure why the following does not return a value for Vend as a string . When I check for the value of vend it says: System.Data.Objects.ObjectQuery``1[System.String]

         string vend = (from vnd in db.Vendors
                 where vnd.VendorID == id
                 select vnd.VendorName).ToString();
    

    When I view the value of vend, it is not what I expected

  • sparkyShorts
    sparkyShorts about 8 years
    I always forget this. Thanks for the concise explanation!