简体   繁体   中英

Creating XName.Get In For Each Loop

I have a LINQ Statement. It searches an XML file. (See example below) There are certain nodes that are required to have information in them. (Not empty) The LINQ Statement returns the transactions that have nodes which are empty, because these are required.

XML File Example:

<OnlineBanking>
  <Transactions>
    <Txn>
      <UserName>John Smith</UserName>
      <CustomerStreet>123 Main</CustomerStreet>
      <CustomerStreet2></CustomerStreet2>
      <CustomerCity>New York</CustomerCity>
      <CustomerState>NY</CustomerState>
      <CustomerZip>12345</CustomerZip>
    </Txn>
  </Transactions>
</OnlineBanking>

LINQ Statement:

//Start LINQ statement
var transactionList =
    from transactions in root.Elements(XName.Get("Transactions")).Elements().AsEnumerable()
    where transactions.Elements().Any
       (
          el =>
          String.IsNullOrEmpty(el.Value) &&
          elementsThatCannotBeEmpty.Contains(el.Name)
       )
    select transactions;

My Question:

I have the required fields (ie. CustomerStreet, CustomerCity, etc) in a database table. Below I have hard coded the XName's that are required. However, I want this to be dynamic from the database.

var elementsThatCannotBeEmpty = new HashSet<XName>
{
   XName.Get("CustomerStreet"),
   XName.Get("CustomerCity"),
   XName.Get("CustomerState"),
   XName.Get("CustomerZip")
};

Here is how I am retrieving the fields that are required from the database:

List<Setting> settingList = SettingsGateway.SelectBySettingType("VerifyField");
foreach (Setting SettingValue in settingList)
{
    string strSettingType = setting.SettingType;
}

How do I take my database result loop and dynamically add XName.Get values?

Thank you so much for your help!

You're trying to check whether Any() of the strings in settingList are empty:

if (settingList.Any(
        name => String.IsNullOrEmpty(el.Element(name).Value)
    )

There is an implicit conversion from string to XName , so you don't actually need to call XName.Get .
If you want to, though, you could write el.Element(XName.Get(name))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM