![](/img/trans.png)
[英]Using LINQ to fill a boolean with true or false based off of condition
[英]get list from xml using linq based on true if there is no true then select false condition tag element in c#
在這里,如果pirmaryCustCheck為true,那么我嘗試獲取custName名稱;否則,我必須選擇false標簽元素,如何實現此xml:
<Root>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>true</pirmaryCustCheck>
<id>8</id>
</customer>
<customer>
<custName> Rahul</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>9</id>
</customer>
</data>
</Root>
代碼:
string pathd = @"C:\Users\admin\documents\newCust.xml";
XDocument docss = XDocument.Load(pathd);
var records = docss.Descendants("data").Select(x => new
{
office = (string)x.Element("office"),
officeId = (string)x.Element("officeId"),
customer = x.Elements("customer").Select(y => new
{
custName = (string)y.Element("custName"),
pirmaryCustCheck = (bool)y.Element("pirmaryCustCheck"),
id = (string)y.Element("id")
}).Where(y => y.pirmaryCustCheck == true).Select(c => new
{
custName = c.custName,
Id = c.id
})
}).FirstOrDefault();
您可能想嘗試以下類似方法。
數據集
<Root>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>true</pirmaryCustCheck>
<id>8</id>
</customer>
<customer>
<custName> Rahul</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>9</id>
</customer>
</data>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>11</id>
</customer>
<customer>
<custName> Rahul Jain</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>10</id>
</customer>
</data>
代碼-
string pathd = @"C:\Users\admin\documents\newCust.xml";
XDocument docss = XDocument.Load(pathd);
var customerTrue = docss.Descendants("data").Elements("customer").Select(x => x).FirstOrDefault();
var customerFalse = docss.Descendants("data").Elements("customer").Select(x => x).LastOrDefault();
var records = docss.Descendants("data").Select(x => new
{
office = (string)x.Element("office"),
officeId = (string)x.Element("officeId"),
customer = new
{
custName = (bool)x.Elements("customer").First().Element("pirmaryCustCheck") ? (string)x.Elements("customer").First().Element("custName") : (string)x.Elements("customer").Last().Element("custName"),
pirmaryCustCheck = (bool)x.Elements("customer").First().Element("pirmaryCustCheck"),
id = (bool)x.Elements("customer").First().Element("pirmaryCustCheck") ? (string)x.Elements("customer").First().Element("id") : (string)x.Elements("customer").Last().Element("id")
}
}).ToList();
請嘗試以下代碼,對其進行測試。
var customers = (from e in docss.Descendants("data").Elements("customer")
where (bool)e.Element("pirmaryCustCheck") == true
select new
{
Name = (string)e.Element("custName"),
Id = (string)e.Element("id"),
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.