我正在从两个不同的来源收集数据,目的是填充单个对象。我的课是
public class SampleClient
{
public string ClientId { get; set; }
public string JobName { get; set; }
public string JobUrl { get; set; }
public string Version { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
第一个LINQ查询填充一个SampleClient对象集合,这些对象获取除Version以外的所有值。然后,我需要遍历第二个查询的集合SampleClient并利用其ClientId值。第二个查询的结果是Version值。这是我的第一个LINQ查询:
private void btnProjects_Click(object sender, EventArgs e)
{
string[] stringArray = { "demo", "sample", "test", "training" };
List<SampleClient> jobList =
(
from x in XDocument.Load(XML URL VALUE HERE).Root.Elements("job")
where x.Element("name").Value.Contains("-config") && x.Element("name").Value.StartsWith("oba-")
&& (!stringArray.Any(s => x.Element("name").Value.Contains(s)))
select new SampleClient
{
ClientId = getClientId((string)x.Element("name")),
JobName = (string)x.Element("name"),
JobUrl = (string)x.Element("url"),
}).ToList();
foreach (SampleClient job in jobList)
{
//Display the results in a textbox
txtResults.Text += "Job Name = " + job.JobName + " | Job URL = " + job.JobUrl + " | ";
}
}
Run Code Online (Sandbox Code Playgroud)
在获取版本的查询中,我目前有:
var version = from item in doc.Descendants(ns + "properties")
select new SampleClient
{
ClientId = strClientId,
Version = (string)item.Element(ns + "product.version").Value
};
Run Code Online (Sandbox Code Playgroud)
重要的是要注意,第二个查询中使用的URL源是使用ClientId从第一个查询中获得的URL源创建的。我可以进行例行循环并清理/合并对象,但这感觉像是黑客。有没有更清洁的方式来处理此问题?
这是第一个查询的XML示例:
<?xml version="1.0"?>
<allView>
<description>PROD</description>
<job>
<name>abc</name>
<url>http://ci-client.company.net/job/abc/</url>
<color>blue</color>
</job>
<job>
<name>acme</name>
<url>http://ci-client.company.net/job/acme/</url>
<color>blue</color>
</job>
</allView>
Run Code Online (Sandbox Code Playgroud)
第二个查询URL是使用第一个查询结果中的clientID动态创建的。我正在使用它来加载Maven POM文件并获取版本信息。这是POM文件中XML的片段。
<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.xyz</groupId>
<artifactId>io</artifactId>
<version>6.11.7-ACME-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<product.version>6.11.7</product.version>
<db.version>1.4</db.version>
</properties>
<modules>
<module>policies</module>
<module>templates</module>
<module>assemble</module>
</modules>
</project>
Run Code Online (Sandbox Code Playgroud)
尝试这个:
var jobList = from x in XDocument.Load(...
where ...
let clientId = getClientId((string)x.Element("name"))
select new SampleClient
{
ClientId = clientId,
JobName = (string)x.Element("name"),
JobUrl = (string)x.Element("url"),
Version = (string)XDocument
.Load(GetSecondQueryUrl(clientId))
.Root
.Element(pom4 + "properties")
.Element(pom4 + "product.version")
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |