Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to return string

Tags:

string

c#

linq

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

like image 471
Nate Pet Avatar asked Nov 21 '11 19:11

Nate Pet


2 Answers

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.

like image 80
Joe Avatar answered Oct 20 '22 19:10

Joe


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().

like image 9
triangle_man Avatar answered Oct 20 '22 19:10

triangle_man