我如何实现嵌套的for循环来构建联系人的搜索工具?

时间:2013-12-23 23:49:51

标签: c# loops for-loop nested

我写了一个简单的程序来存储联系人号码,输入的数据是假的,我计划稍后更新,但我基本上想添加一个嵌套的for循环来添加一个搜索工具,可以有人帮我吗?圣诞节快乐的人:))

到目前为止,这是我的编码:

//declare variables
int iRow;
string sSearch;

//Declare arrays
string[,] sContacts = new string[,] {
                                      {"John", "07621456900"},
                                      {"Jasper", "07843456377"},
                                      {"June", "07935254678"},
                                      {"Jim", "07945112623"},
                                      {"Jackie", "07431733507"}, };

//Search facility for contacts
Console.WriteLine("Who would you like to search for?");
sSearch = Console.ReadLine();

//Display a heading
Console.Clear();
Console.WriteLine("My top 5 contacts are: ");
Console.WriteLine();

//Display the names and numbers (using a for loop)
for (iRow = 0; iRow < sContacts.GetLength(0); iRow++)
{
    Console.WriteLine(sContacts[iRow, 0] + ": " + sContacts[iRow, 1]);   //The [0] indicates the first section of the array (The name), 
    //and [1] indicates the second (The phone number)
    Console.WriteLine();
}

//Prevent program from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();

2 个答案:

答案 0 :(得分:1)

强烈要求您使用Dictionary而不是Multi-Dimensional Array。代码更易于管理和阅读。此外,在Dictionary中搜索值更直观,更容易。

我为你写了一个小例子:

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         // Declare Dictionary
         Dictionary<string, string> dContacts = new Dictionary<string, string>();
         dContacts.Add("John", "07621456900");
         dContacts.Add("Jasper", "07843456377");
         dContacts.Add("June", "07935254678");
         dContacts.Add("Jim", "07945112623");
         dContacts.Add("Jackie", "07431733507");

         // Search facility for contacts
         Console.WriteLine("Who would you like to search for?");
         Console.Clear();

         Console.WriteLine("My top 5 contacts for that name are: ");
         Console.WriteLine();
         foreach (KeyValuePair<string, string> kvPair in dContacts)
         {
            Console.WriteLine("Name: {0} " + "- " + "Number: {1} ", kvPair.Key, kvPair.Value);
            Console.ReadKey();
         }
         // Prevent program from closing
         Console.WriteLine("Press any key to close");
         Console.ReadKey();
      }
   }
}

注意:我没有连接您的搜索功能,只是为了简洁起见而删除它。

答案 1 :(得分:0)

你可以使用Dictionary<string, string>作为@Brian提到的。我个人从未在任何工作中见过string[,]

或者您可以通过创建一个类来添加更多语义。

public class Person
{
    public string Name { get; set; }
    public string Number { get; set; }
}

用以下代码替换你的代码:

List<Person> contacts = new List<Person>();

contacts.Add(new Person { Name = "John", Number = "07621456900" });
contacts.Add(new Person { Name = "Jasper", Number = "07843456377" });
contacts.Add(new Person { Name = "June", Number = "07935254678" });
contacts.Add(new Person { Name = "Jim", Number = "07945112623" });
contacts.Add(new Person { Name = "Jackie", Number = "07431733507" });

List<Person>是另一种广泛使用的类型。这非常有用。

现在循环和查找联系人要容易得多。您只需使用foreach

即可
Person personFound = null;

foreach (Person c in contacts)
{
    if (c.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
    {
        personFound = c;
        break;
    }
}

我正在使用String.Equals(string, StringComparison),它允许我以不区分大小写的方式比较字符串。

查找内容的另一种方法是使用Linq

// finds the first contact with the name specified or
// return the default value for Person (null)
Person contact = contacts
    .FirstOrDefault(o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));

并输出联系方式,如果找到:

if (contact != null)
{
    Console.WriteLine("Found: {0}, Number: {1}", contact.Name, contact.Number);
}
else
{
    Console.WriteLine("Not found");
}

还有一件事,你不应该命名sContacts,检查MSDN General Naming Convertions,它说

  

X请勿使用匈牙利表示法。

匈牙利表示法是:

  

匈牙利表示法是计算机编程中的标识符命名约定,其中变量或函数的名称表示其类型或用途。


如果您出于某种神秘的原因必须真正使用string[,],可以这样做:

string[] contact = null;

for (int i = 0; i < sContacts.Length; i++)
{
    if (sContacts[i, 0].Equals(name, StringComparison.InvariantCultureIgnoreCase))
    {
        contact = new string[2];
        contact[0] = sContacts[i, 0];
        contact[1] = sContacts[i, 1];
        break;
    }
}

你看到你还需要做多少工作?它没有语义,很难知道这些值是什么意思......至少在这里使用这种类型是不值得的。

如果你有了:

string[][] contacts = new string[5][]
{
    new string[] {"John", "07621456900"},
    new string[] {"Jasper", "07843456377"},
    new string[] {"June", "07935254678"},
    new string[] {"Jim", "07945112623"},
    new string[] {"Jackie", "07431733507"},
};

然后你可以使用嵌套的for循环,但是你不需要,你只需要访问[0]按名称搜索,或[1]按号码搜索。

for (int i = 0; i < contacts.Length; i++)
{
    // for (int j = 0; j < contacts[i].Length; j++)

    if (contacts[i][0].Equals(name, StringComparison.InvariantCultureIgnoreCase))
    {
        contact = contacts[i];
        break;
    }
}