GibboK
GibboK

Reputation: 73908

Linq - Retrieve a single value in a String

I use Asp.net 3.5 and EF 4.

I need find a specific row in my DataBase and display on a label a single value as string.

At the moment I use this code, it is working, so I find a single Object and read its properties.

 var myAuthor = (from at in context.CmsAuthors
             where at.AuthorId == myRow.AuthorId
             select at).Single();   
 myAuthorNameLabel.Text = myAuthor.LastName;

I would like to know:

Upvotes: 0

Views: 14224

Answers (2)

Variant
Variant

Reputation: 17365

You can use:

 var myAuthorName = 
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);

actually this would be even better:

var myAuthorName = 
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();

Update

An example of how to use with Anonymous type:

var myAuthorNames = 
    (from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();

Upvotes: 3

Bala R
Bala R

Reputation: 108947

Here's the method syntax (using lambdas)

myAuthorNameLabel.Text = context.CmsAuthors
                           .Where(at => at.AuthorId == myRow.AuthorId)
                           .Select(at => at.LastName) 
                           .SingleOrDefault() ?? string.Empty;

Upvotes: 4

Related Questions