views:

54

answers:

3

Hi All,

I have a quick linq question. I have a stored proc that should return one row of data. I would like to use a lambda 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 }

+1  A: 

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

Codesleuth
+2  A: 

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");
}
Bryan Watts
Why create an instance of the class in this line: var location = new GeoLocationDC();only to throw it away later on in this line: location = new GeoLocationDC {... };
Chris Dunaway
@Chris Dunaway: Only because that was how the OP had structured the code. I changed it to reflect how I would write it.
Bryan Watts
A: 

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

(

Khnle