2010-08-26 84 views
0

我正在使用LINQ與C#.NET程序中的數據集中的數據進行交互。數據從XML文件導入到數據集中,以便獲取它的模式。我希望能夠從表中獲取單行,然後以強類型的方式(具有智能感)訪問該行的特定列。我認爲我的語法很接近,但我不太明白。這裏是我迄今爲止...如何使用LINQ獲取強類型單值使用LINQ

// 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 

這個例子的工作,但我想這樣做沒有foreach循環...

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); 
} 

任何想法?

回答

0

如果我正確地得到你的問題,然後:

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

在括號包裹,並添加SingleOrDefault()