2012-03-10 15 views
0

これで、「完了できませんでした」という結果に終わることがありますが、私は特定の質問に対する答えを見つけられませんでした。変数を使用してオブジェクトを初期化する

私の問題は、生徒の詳細を保持するための構造体を持っていることです.2人の学生がいると言います。もう1人はMikeと呼ばれ、それぞれの詳細を画面に表示したいと思います。 so:

public struct student{ 
    public String name, course; 
    public int year, studentno; 

    public void displayDetails(){ 
     Console.WriteLine("Name: "+name); 
     Console.WriteLine("Course: "+course); 
     Console.WriteLine("Student Number: "+studentno); 
     Console.WriteLine("Year of Study: "+year); 
     Console.WriteLine("\n\nPress any key to Continue...."); 
     Console.ReadKey(); 
    } 
} 

詳細を表示するには、Mike.displayDetails();を使用します。またはDave.displayDetails();

ユーザーの名前を入力してその名前を使用して正しい生徒を取得する方法はありますか?これはなんとかです、

surname.displayDetails(); 

が正しい学生を表示するには:例えば私が使用したい:

Console.Write("Please enter students name: "); 
String surname = Console.ReadLine(); 

をして、何とかでしょうか?

答えて

6

extension methodは文字列型で実行できますが、必ずしも推奨されません。 LINQを使用して、特定の姓の学生を学生集団の上に配置するのはなぜですか?注意すべき

List<Student> students 
    = new List<Student> 
     { 
     new Student { Surname = "Smith" }, 
     new Student { Surname = "Jones" } 
     }; 

Student studentJones = students.FirstOrDefault(s => s.Surname == "Jones"); 

その他の見所:

  • あなたが使用することを避け
  • 方法とタイプ名のためにそう
  • 使用PascalCaseを行うには十分な理由がない限り、クラスではなく、構造体を使用しますパブリックフィールドの代わりにプロパティを使用する
3

あなたはそれらを辞書に入れることができます。

Dictionary<string, Student> dict = new Dictionary<string, Student>(); 
dict.Add("Dave", Dave); 
dict.Add("Mike", Mike); 
string surname = Console.ReadLine(); 
dict[surname].DisplayDetails(); 

ところで、辞書から検索は、一般に、高速(O(1))FirstOrDefaultが行う(O(n))は、リストを見ているよりも長いです。

0

クラスを作成し、KeyedCollectionから派生させます。生徒の名前にキーを設定します。各学生がコレクションに追加されると、次の電話番号に電話することができます。

Console.Write(myCollection[surname].DisplayDetails()); 



public class Students : KeyedCollection<string, Student> 
{ 
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed. 
    // 
    public Students() : base() {} 

    // This is the only method that absolutely must be overridden, 
    // because without it the KeyedCollection cannot extract the 
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument, 
    // in this case string. 
    // 
    protected override string GetKeyForItem(Student item) 
    { 
     // In this example, the key is the student's name. 
     return item.Name; 
    } 
} 
関連する問題