我馬上要說 - 我是一個認真的初學者,這是我的學習專案。我正在嘗試創建一種方法,管理員可以搜索滿足特定條件的帳戶。首先,系統會提示他輸入所有引數,然后我只想使用具有某些輸入的引數來搜索滿足所有條件的帳戶。
如果所有引數都有一些輸入,這里是搜索陣列的部分:
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,但由于我必須對所有組合執行此操作,因此很多代碼似乎沒有必要。肯定有一種更有效的方法來做到這一點,我只是沒有看到。
有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
我會這樣做:(
您必須根據資料型別調整每行的第一部分(空檢查))
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 ...
}
uj5u.com熱心網友回復:
你仍然可以使用 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}");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402373.html
標籤:
上一篇:在C#中檢查串列項
