tags:

views:

51

answers:

2

I am using LINQ to interact with data in a DataSet in a C#.NET program. The data is imported into the data set from an XML file so that is where it gets it's schema. I want to be able to grab a single row from the table and then access the specific columns of that row in a strongly-typed manner (with intelli-sense). I think I am close on the syntax but I can't quite get it. Here's what I have so far...

// RunnerDataTable contains columns named FirstName, LastName, etc.
   var OneRunner = RunnerDataTable().Single( p => p.Field<string>("FirstName") == "Jordan");
   MessageBox.Show(OneRunner.LastName);  // This doesn't work

This example does work but I would like to do it without the foreach loop...

var SomeRunners= from f in RunnerDataTable.AsEnumerable()
                                where f.Field<string>("FirstName") == "Jordan"
                                select new { FirstName = f.Field<string>("FirstName"), LastName = f.Field<string>("LastName")};
foreach (var o in SomeRunners)
{
    MessageBox.Show(o.FirstName + " " + o.LastName); 
}

Any ideas?

+1  A: 
var OneRunner = (from f in RunnerDataTable.AsEnumerable()
                 where f.Field<string>("FirstName") == "Jordan"
                 select new { FirstName = f.Field<string>("FirstName"), 
                              LastName = f.Field<string>("LastName")}
                 ).SingleOrDefault();

Wrap in parens and add SingleOrDefault()

Jay
A: 

If I get your question correctly, then:

var OneRunner = (
  from f in RunnerDataTable.AsEnumerable()
  where f.Field<string>("FirstName") == "Jordan"
  select new
    {
       FirstName = f.Field<string>("FirstName"),
       LastName = f.Field<string>("LastName")
    }
 ).Single();
Jon Hanna