2014-10-30 65 views
-5

我想用此代碼中的ID搜索 當用戶將此ID(標題,名稱,電話號碼)的信息寫入ID display 如何實現它?在c#中搜索

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()); 
    } 
    } 
} 
+1

在MSDN上查找'FirstOrDefault'。你有嘗試過什麼嗎? – BradleyDotNET 2014-10-30 22:40:00

+0

並不使用數組,但'列表' – Steve 2014-10-30 22:41:25

+0

我知道,但我需要在這個任務中使用數組 – 2014-10-30 23:33:54

回答

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;到文件的頂部。

+0

謝謝蒂姆;) – 2014-10-30 23:04:40