时间:2019-03-17 标签:c#LINQQuery
我有以下代码:
var tableID = from data in studyData.Tables["MX_MD_TABLE"].AsEnumerable()
where data.Field<string>("table_name").ToLower() == "mbddx_study_set"
select data.Field<long>("ID").ToString();
string tableID = tableID.ElementAt(0).ToString();
它按预期工作,tableID 就是我想要的。有没有办法让 LINQ 查询实际返回并将返回的字符串存储为它的值,而不必创建另一个对象来保存它?我知道这个查询和我将要做的其他一些查询只会返回单个字符串。
谢谢。
I have the following code:
var tableID = from data in studyData.Tables["MX_MD_TABLE"].AsEnumerable()
where data.Field<string>("table_name").ToLower() == "mbddx_study_set"
select data.Field<long>("ID").ToString();
string tableID = tableID.ElementAt(0).ToString();
It works as expected and the tableID is what I want. Is there a way for the LINQ query to actually return and store the returned string in as it's value, rather than having to create another object to hold it? I know that this query and a few others I will be doing, will only return the single string.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能就是您想要的(请注意 FirstOrDefault 的使用):
这 将选择表中找到的第一个符合所需条件的元素,而不是返回集合;无论如何,元素的
ID
应该是唯一的,因此我怀疑您应该只寻找单个元素。请注意,它还返回由
Field
定义的预期类型的值,因此此时您只需在tableID
上调用ToString
code> 检查后返回了一些内容 - 但不要将其附加到FirstOrDefault
调用,因为这可能返回 null。This might be what you want (note the use of FirstOrDefault):
This will select the first element found in the table that falls within the desired criteria, as opposed to returning a collection; the
ID
's of elements ought to be unique anyway so you should only ever be looking for a single one, I'd suspect.Note that it also returns the value as it's expected type as defined by
Field<long>
, so at this point you just need to callToString
ontableID
after checking it returned something - but don't append it to theFirstOrDefault
call as that could return null.尽管我质疑您在数据表上使用 LINQ 来返回标量值。
编辑:
LINQ 非常好用,而且非常强大,但也非常昂贵。 DataTables 有自己内置的方式来搜索数据并返回结果。
请参阅 http://msdn.microsoft.com/en MSDN 上的 -us/library/y06xa2h1(v=VS.100).aspx 为例。
Although I question your use of LINQ on a datatable to return a scalar value.
Edit:
LINQ is great and useful and very powerful, but also very expensive. DataTables have their own built-in way to search for data and return results.
See http://msdn.microsoft.com/en-us/library/y06xa2h1(v=VS.100).aspx on MSDN for an example.