LINQ Statement WHERE Question

本文关键字:Question WHERE Statement LINQ | 更新日期: 2023-09-27 18:02:11

我返回一个列表。它包含xml文件中不能为空的xml节点的名称。

List<Setting> settingList = SettingsGateway.GetBySettingTypeList("VerifyField");

我有一个LINQ语句。我试图返回所有具有空节点的事务。这里的列表返回的是不能为空的节点。有人知道我做错了什么吗?

下面的代码应该将"事务"绑定到DataGrid,并显示具有所需的空节点的Txn。

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)
    settingList.Any(
        name => String.IsNullOrEmpty(el.Element(name.SettingValue).Value)
    )
)
select new
{
    CustomerName = transactions.Element(XName.Get("CustomerName")).Value,
    ConfirmationNumber = transactions.Element(XName.Get("ConfirmationNumber")).Value
 };
 GridView.DataSource = transactionList;
 GridView.DataBind();

XML文件示例:

<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 WHERE Question

好,第一个问题:如果元素缺失,您将得到一个NullReferenceException。

我建议创建一个不能为null的元素的List<string>,以使查询简单。然后:

var requiredElements = settingList.Select(x => x.SettingValue).ToList();
var transactionList = root
      .Elements("Transactions")
      .Elements("Txn")
      .Where(x => requiredElements
                    .Any(name => string.IsNullOrEmpty((string) x.Element(name)));

认为应该没问题,并且比原始代码稍微简单一些…但说实话,您的原始代码看起来应该可以正常工作。它到底做了什么?你对实际结果和预期的结果还不是很清楚。

像这样:

var transactionList =
     root
    .Elements(XName.Get("Transactions")) //Get <Transaction> elements
    .Elements() //Get <Txn> elements
    .Where(txn => txn.Elements().Any(e => e.Value == String.Empty))  //Filter <Txn> Elements if it have any element like this: <CustomerStreet2></CustomerStreet2>
    .Select(x => new {
        PropertyX = x.Element(XName.Get("UserName")),
        PropertyY = x.Element(XName.Get("CustomerStreet")),
                    ...
    });

处理:

<OnlineBanking>
  <Transactions>
    <Txn> <!-- This one matches! -->
      <UserName>John Smith</UserName>
      <CustomerStreet>123 Main</CustomerStreet>
      <CustomerStreet2></CustomerStreet2> 
      <CustomerCity>New York</CustomerCity>
      <CustomerState>NY</CustomerState>
      <CustomerZip>12345</CustomerZip>
    </Txn>
    <Txn> <!-- This one doesn't match! -->
      <UserName>John Smith</UserName>
      <CustomerStreet>123 Main</CustomerStreet>
      <CustomerStreet2>ASDASD</CustomerStreet2>
      <CustomerCity>New York</CustomerCity>
      <CustomerState>NY</CustomerState>
      <CustomerZip>12345</CustomerZip>
    </Txn>
  </Transactions>
</OnlineBanking>