开发者

How can I use linq to build an object from 1 row of data?

I have a quick linq question. I have a stored proc that should return one row of data. I would like to use a lambd开发者_Go百科a to build an object. Here's what I'm currently doing which works, but I know I should be able to use First instead of Select except I can't seem to get the syntax correct. Can anyone straighten me out here? Thanks for any help.

 var location = new GeoLocationDC();
 DataSet ds = db.ExecuteDataSet(dbCommand);
 if(ds.Tables[0].Rows.Count == 1)
            {
                 var rows = ds.Tables[0].AsEnumerable();
                 var x = rows.Select(
                     c => new GeoLocationDC
                              {
                                  Latitude = Convert.ToInt32(c.Field<string>("LATITUDE")),
                                  Longitude = Convert.ToInt32(c.Field<string>("LONGITUDE"))
                              }).ToList();
                 if(x.Count > 0 )
                 {
                     location = x[0];
                 }

Cheers, ~ck }


You don't need to use Select - since you know there is exactly 1 row, you can use it directly:

var location = new GeoLocationDC();
var ds = db.ExecuteDataSet(dbCommand);

if(ds.Tables[0].Rows.Count == 1)
{
    var row = ds.Tables[0].AsEnumerable().Single();

    location.Latitude = row.Field<int>("LATITUDE");
    location.Longitude = row.Field<int>("LONGITUDE");
}


If you know your data is always 1 record, .Select is fine. Otherwise you'd have to do .First().Select() anyway.


Dropping the temporary variable x, and the need to check for count, you can do like this:

var location = rows.Select(c => new GeoLocationDC
    {
        Latitude = Convert.ToInt32(c.Field<string>("LATITUDE")),
        Longitude = Convert.ToInt32(c.Field<string>("LONGITUDE"))
    }).First(); //or better yet, use FirstOrDefault()

(

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜