【问题标题】:How to search through an array of objects using only variables that user provided input for如何仅使用用户提供输入的变量来搜索对象数组
【发布时间】:2022-01-01 20:05:35
【问题描述】:

我马上要说 - 我是一个认真的初学者,这是我的学习项目。 我正在尝试制作一种方法,管理员可以搜索满足特定条件的帐户。 首先,系统会提示他输入所有参数,然后我只想使用有一些输入的参数来搜索满足所有条件的帐户。

如果所有参数都有一些输入,这是它搜索数组的部分:

for (int index = 0; index < objAccount.Length; index++)
        {
            if (objAccount[index].accNum == accNum && objAccount[index].accLogin == accLogin && objAccount[index].accName == accName && objAccount[index].accBalance == accBalance && objAccount[index].accType == accType && objAccount[index].accStatus == accStatus)
            {
                Console.WriteLine($"{objAccount[index].accNum,15}" + $"{objAccount[index].accLogin,15}" + $"{objAccount[index].accName,20}" + $"{objAccount[index].accBalance,15:C}" + $"{objAccount[index].accType,15}" + $"{objAccount[index].accStatus,15}");
            }
        }

以我有限的知识,我想出的一个解决方案是对所有参数执行 if/else ifs,但由于我必须对所有组合都这样做,所以很多代码似乎是不必要的。肯定有一种更有效的方法来做到这一点,而我只是没有看到。

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: c# .net console-application


【解决方案1】:

我会这样做:
(您必须根据数据类型调整每行的第一部分(空检查))

var filtered = objAccount.Where( x => 
    (accNum == null || x.accNum == accNum) && 
    (accLogin == null || x.accLogin == accLogin) && 
    (String.IsNullOrEmpty(accName) || x.accName == accName) && 
    (accBalance == null || x.accBalance == accBalance) && 
    (accType == null || x.accType == accType) && 
    (accStatus == null || x.accStatus == accStatus)
);

foreach (var item in filtered)
{
    Console.WriteLine ...
}

【讨论】:

    【解决方案2】:

    你仍然可以使用 foreach 来逃避双重迭代

    foreach (var item in objAccount)
    {
     if (
      (accNum == null || item.accNum == accNum) &&
      (accLogin == null || item.accLogin == accLogin) &&
      (string.IsNullOrEmpty(accName) || item.accName == accName) &&
      (accBalance == null || item.accBalance == accBalance) &&
      (accType == null || item.accType == accType) &&
      (accStatus == null || item.accStatus == accStatus)
     )
        Console.WriteLine($" {item.accNum,15} {item.accLogin,15} {item.accName,20} { item.accBalance,15:C}{ item.accType,15}{ item.accStatus,15}");
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2013-04-19
      • 1970-01-01
      • 2020-07-18
      • 2017-08-17
      相关资源
      最近更新 更多