开发者

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:

  • If there is another syntax in Linq to achieve the same result.
  • How to do it using 开发者_Python百科Lamba?
  • Which approach would you suggest me?


Here's the method syntax (using lambdas)

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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜