如何使用 linq 从 1 行数据构建对象?
我有一个快速的 linq 问题。我有一个应该返回一行数据的存储过程。我想使用 lambda 来构建一个对象。这是我目前正在做的工作,但我知道我应该能够使用 First 而不是 Select,除非我似乎无法获得正确的语法。有人能在这里纠正我吗?感谢您的任何帮助。
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];
}
干杯, 〜ck }
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要使用
Select
- 因为您知道正好有 1 行,所以您可以直接使用它:You don't need to use
Select
- since you know there is exactly 1 row, you can use it directly:如果您知道您的数据始终为 1 条记录,则
.Select
就可以了。否则你无论如何都必须执行.First().Select()
。If you know your data is always 1 record,
.Select
is fine. Otherwise you'd have to do.First().Select()
anyway.删除临时变量x,并且需要检查计数,你可以这样做
:(
Dropping the temporary variable x, and the need to check for count, you can do like this:
(