条件 var 推断类型查询 LINQ to XML 的替代编码?
这是此处找到的相关主题的后续内容 https://stackoverflow.com/questions/1987485/conditionally- 则分配-c-var-as-elegant-as-it-gets
如果我执行以下操作,
var query = (SearchString == "" ?
(
from MEDIA in xdoc.Descendants("MEDIA")
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
):
from MEDIA in xdoc.Descendants("MEDIA")
where MEDIA.Element("TTL").ToString().ToLower().Contains(SearchString)
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
) ;
:如何声明查询类型以使其在类级别静态?
或者,在引用的帖子 Marc Gravell 中指出了一种不同的方法:
IQueryable<Part> query = db.Participant;
if(email != null) query = query.Where(p => p.EmailAddress == email);
if(seqNr != null) query = query.Where(p => p.SequenceNumber == seqNr);
...
在我的情况下,我将如何声明/重新编码查询? 这是我的疯狂尝试:)
IEnumerable<XElement> query = xdoc.Descendants("MEDIA");
if (SearchString != "" )
query = query.Where(m => m.Element("TTL").ToString().ToLower().Contains(SearchString));
谢谢。
This is a follow up on a related topic found here
https://stackoverflow.com/questions/1987485/conditionally-assign-c-var-as-elegant-as-it-gets
if I am doing the following:
var query = (SearchString == "" ?
(
from MEDIA in xdoc.Descendants("MEDIA")
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
):
from MEDIA in xdoc.Descendants("MEDIA")
where MEDIA.Element("TTL").ToString().ToLower().Contains(SearchString)
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
) ;
How would I declare the query type to make it static at the class level?
Alternatively, in the referenced post Marc Gravell point out a different approach
IQueryable<Part> query = db.Participant;
if(email != null) query = query.Where(p => p.EmailAddress == email);
if(seqNr != null) query = query.Where(p => p.SequenceNumber == seqNr);
...
How would I declare/recode the query in my case?
Here is my wild attempts :)
IEnumerable<XElement> query = xdoc.Descendants("MEDIA");
if (SearchString != "" )
query = query.Where(m => m.Element("TTL").ToString().ToLower().Contains(SearchString));
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能。匿名类型是匿名的......所以它们没有可用于声明变量的名称。您的查询的类型为
IEnumerable
,但您无法在代码中引用something
。因此,您需要创建一个表示查询结果的特定类,并使用它而不是匿名类型。You can't. Anonymous types are, well, anonymous... so they don't have a name you can use to declare variables. Your query is of type
IEnumerable<something>
, but you can't refer tosomething
in your code. So you need to create a specific class that represent the results of your query, and use it instead of the anonymous type.