【问题标题】:Searching In c# [closed]在c#中搜索[关闭]
【发布时间】:2014-12-27 04:15:40
【问题描述】:

我想在此代码中使用 ID 进行搜索 当用户写 id 时这个 ID 的信息(title , name , phone)显示 我该如何实施?

namespace Search
{
 class Program
 {
     static void InputStudent(Student x)
     {
        Console.WriteLine("Please enter a User:");
        Console.WriteLine("User ID:");
        x.ID = int.Parse(Console.ReadLine());
        Console.WriteLine();

        Console.WriteLine("Titel:");
        x.Titel = Console.ReadLine();

        Console.WriteLine("Name:");
        x.Name = Console.ReadLine();

        Console.WriteLine("Telephone Number:");
        x.Telephone = int.Parse(Console.ReadLine());
        Console.WriteLine();  
    }

    static void Main()
    {
        Student[] st = new Student[3];

        for (int i = 0; i < st.Length; i++)
        {
            st[i] = new Student();
            InputStudent(st[i]);
        }

        int IDs;
        Console.Write("Please enter the number of ID you want to search for ");
        IDs = Convert.ToInt32(Console.ReadLine());
    }
  }
}

【问题讨论】:

  • 在 MSDN 上查找 FirstOrDefault。你试过什么吗?
  • 并且不要使用数组而是使用List&lt;Student&gt;
  • 我知道,但是我需要在这个任务中使用数组

标签: c# arrays class search console-application


【解决方案1】:

你可以使用LINQ,例如Enumerable.FirstOrDefault:

Student firstWithID = st.FirstOrDefault(s => s.ID == IDs);
if( firstWithID != null )
{
    Console.WriteLine("User ID: {0} Titel: {1} Name: {2} Telephone Number: {3}"
        , firstWithID.ID
        , firstWithID.Titel
        , firstWithID.Name
        , firstWithID.Telephone);
}

您需要在文件顶部添加using System.Linq;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2016-07-27
    • 2018-09-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多