我有一个字符串列表
List<string> lststr = new List<string>() { "1,", "2" };
我需要生成以下
<DbRuleMappings>
<DbRuleMapping dbDetailId="1" ruleMasterId="1" activeFlag="1" />
<DbRuleMapping dbDetailId="1" ruleMasterId="2" activeFlag="1" />
<DbRuleMapping dbDetailId="1" ruleMasterId="3" activeFlag="1" />
<DbRuleMapping dbDetailId="1" ruleMasterId="4" activeFlag="1" />
<DbRuleMapping dbDetailId = "2" ruleMasterId="1" activeFlag="1"/>
<DbRuleMapping dbDetailId = "2" ruleMasterId="2" activeFlag="1"/>
<DbRuleMapping dbDetailId = "2" ruleMasterId="3" activeFlag="1"/>
<DbRuleMapping dbDetailId = "2" ruleMasterId="4" activeFlag="1"/>
</DbRuleMappings>
我的尝试......没有工作
List<string> lststr = new List<string>() { "1,", "2" };
XDocument docDBRuleMapping =
new XDocument(
new XElement("DbRuleMappings",
Enumerable.Range(1, 4).Select(x => x)
.Select(i => new XElement("DbRuleMapping",
new XAttribute("dbDetailId", i),
new XAttribute("ruleMasterId", i),
new XAttribute("activeFlag", 1)))));
答案 0 :(得分:1)
您目前根本没有使用lststr
。您需要基本上使用SelectMany
与lststr
加入Enumerable.Range
。使用查询表达式可能最容易完成:
var detailIds = new List<int> { 1, 2 };
var doc = new XDocument(new XElement("DbRuleMappings",
from detailId in detailIds
from ruleId in Enumerable.Range(1, 4)
select new XElement("DbRuleMapping",
new XAttribute("dbDetailId", detailId),
new XAttribute("ruleMasterId", ruleId),
new XAttribute("activeFlag", 1))));
(我已经将输入更改为List<int>
而不是List<string>
给定数据...如果您确实需要,它会与List<string>
一起正常工作。
如果您不喜欢查询表达式,请参阅以下内容:
var detailIds = new List<int> { 1, 2 };
var doc = new XDocument(new XElement("DbRuleMappings",
detailIds.SelectMany(_ => Enumerable.Range(1, 4),
(detailId, ruleId) => new XElement("DbRuleMapping",
new XAttribute("dbDetailId", detailId),
new XAttribute("ruleMasterId", ruleId),
new XAttribute("activeFlag", 1)))));