简体   繁体   English

如何使用c#xelement动态过滤?

[英]How to filter dynamically using c# xelement?

I have done my searching and was not able to find a solution to problem that I have. 我已经完成了我的搜索,但无法找到解决问题的方法。

I'm a bit new to c#.net. 我对c#.net有点新鲜。

Here is my problem. 这是我的问题。 I am trying to dynamically filter xelement. 我正在尝试动态过滤xelement。

The number of attribute and the value of the attributes are not known, and will depend on some other routine/process. 属性的数量和属性的值是未知的,并且将取决于一些其他例程/过程。

these my attribute name to filter, can be one or more attribute to filter. 这些我要过滤的属性名称,可以是一个或多个要过滤的属性。

string[] param = new string[] { "techcode", "productgroup", "photolayer" }

my xml file is in this form: 我的xml文件采用以下格式:

<?xml version="1.0" encoding="utf-8"?>
<threads>
  <thread techcode="sometech" productgroup="pgroup" 
          photolayer="player" biasewma="-0.05" />
</threads>

I can filter succesfully if i hardcoded something like this 如果我硬编码这样的东西,我可以成功过滤

IEnumerable<XElement> singlethread = (from el in apcxmlstate.Elements("thread")
  where 
    (string)el.Attribute("techcode") == somevalue
    && (string)el.Attribute("productgroup") == somevalue
    && (string)el.Attribute("photolayer") == somevalue
  select el);

However, this is not what I want, because I will not know which attribute do I exactly want to filter. 但是,这不是我想要的,因为我不知道我想要过滤哪个属性。 It will be generated dynamically. 它将动态生成。

For example, at run time, attribute that I want to filters are techcode and productgroup only. 例如,在运行时,我想要过滤的属性仅为techcode和productgroup。 Would any kind soul help me to provide suggestion. 任何善良的灵魂都会帮我提供建议。

You can build query dynamically: 您可以动态构建查询:

IEnumerable<XElement> query = apcxmlstate.Elements("thread");

foreach(var name in param)
   query = query.Where(t => (string)t.Attribute(name) == someValue);

UPDATE: I think your problem is that instead of single someValue variable you are trying to get different values for each attribute. 更新:我认为您的问题是,您尝试为每个属性获取不同的值,而不是单个someValue变量。 But only last one is captured in lambda. 但只有最后一个是在lambda中捕获的。 You need to create local variable to store value for each lambda: 您需要创建局部变量来存储每个lambda的值:

IEnumerable<XElement> singlethread = apcxmlstate.Elements("thread"); 

foreach (var name in param) {
   var value = row[name].ToString();
   singlethread = singlethread.Where(t => (string)t.Attribute(name) == value); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM