我正在使用LINQ与C#.NET程序中的DataSet中的数据进行交互。数据从XML文件导入到数据集中,这样就可以获得它的模式。我希望能够从表中获取单行,然后以强类型方式访问该行的特定列(具有智能感)。我想我的语法很接近,但我不太明白。这是我到目前为止所拥有的......
// 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 :(得分: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();
包裹parens并添加SingleOrDefault()
答案 1 :(得分: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();