【问题标题】:Search function in c# consolec#控制台中的搜索功能
【发布时间】:2019-09-30 14:26:56
【问题描述】:

我正在c# 中制作一个控制台项目来制作搜索功能。它将询问名称并从数组中检查并找到它们以显示总余额。

如何制作一个搜索功能并在其他功能中使用?

void total_bank_balance()
{
  Console.WriteLine("Please Enter the name for check the total balance");
  name = Console.ReadLine();
  for ( int k = 0; k < b; k++ )
  {
    if ( customer_name[k] == name )
    {
      Console.WriteLine(customer_name[k] + " Your total bank balance is " + bank_balance[k]);
      break;
    }
    else
    {
      Console.WriteLine("The Customer is not present in our database");
    }
  }
}

我正在手动搜索,但我想创建一个搜索功能并在银行总余额中使用它,并在他们搜索时显示他在银行中的金额。

输出应该像做一个搜索功能并使用关于使用代码的银行余额总额,它应该使用代码可读性。

【问题讨论】:

  • 您当前的代码会在每次通过循环时说客户不在数据库中,直到找到匹配的名称才匹配。如果未找到匹配项,则在循环结束之前不应打印该消息。
  • 请编辑您的问题并指出有关您的阵列和总余额的更多信息。添加一些数据样本。

标签: c# string search console


【解决方案1】:

如果这更多是关于代码可读性,这是我的方法

public class Customer
{
    public string Name { get; set; }
    public decimal Balance { get; set; }
}

private List<Customer> CustomerList { get; set; }

void TotalBankBalance()
{
    Console.WriteLine("Please Enter the name for check the total balance");
    string SearchTerm = Console.ReadLine();
    Customer SearchResult = CustomerList.FirstOrDefault(x => x.Name == SearchTerm);

    if (SearchResult != null)
    {
        Console.WriteLine("{0} your total bank balance is {1:C2}", SearchResult.Name, SearchResult.Balance);
    }
    else
    {
        Console.WriteLine("The Customer is not present in our database");
    }
}
  1. 为您的客户使用自定义类
  2. 将客户保留在一个列表中,而不是与他们的余额分开
  3. 个人口味,但将snake_case 和CamelCase 混淆在我的眼睛里很痛
  4. 使用Linq 缩短循环

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2013-12-12
    • 2016-08-06
    • 1970-01-01
    • 2011-06-24
    • 2015-09-30
    • 1970-01-01
    • 2021-04-03
    • 2019-04-15
    相关资源
    最近更新 更多