I have a list of string
List<string> lststr = new List<string>() { "1,", "2" };
I need to generate the below
<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>
My attempt ...not working
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)))));
You're currently not using lststr
at all. You need to basically use SelectMany
to join lststr
with your Enumerable.Range
. That's probably done most easily with a query expression:
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))));
(I've changed the input to be a List<int>
rather than a List<string>
given the data... it would work fine with a List<string>
if you really need that though.
If you don't like query expressions, here's the equivalent without:
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)))));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.