Straight away I'm gonna say - I'm a serious beginner and this is for my learning project. I am trying to make a method where an admin can search for accounts meeting specific criteria. First, he is prompted for input for all the parameters and then I want to use only the ones that have some input to search for the accounts meeting all criteria.
Here is a part where it searches through an array if all parameters have some input:
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}");
}
}
With my limited knowledge, one solution I came up with was to do if/else ifs for all parameters but since I would have to do that for all combinations it would be a lot of code that seems unnecessary. There surely must be a more efficient way to do this that I'm just not seeing.
Could anyone help me with this one?
CodePudding user response:
I would do it like this:
(You have to adjust the first part of each line (null check) according to the dataTypes)
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 ...
}
CodePudding user response:
you can still use foreach to escape double iteration
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}");
}