1

我有一个字符串列表

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)))));
4

1 回答 1

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))));

(我已经将输入更改为 aList<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)))));
于 2013-07-02T06:02:48.987 回答