2017-06-09 49 views
0

如何創建一個方法GetStudents()它將返回所有學生的列表。 GetStudents()的返回類型是List,其中int = id和string = name?帶返回類型的方法列表<int,string>

該方法需要在visual studio中創建。

+0

你可以返回一個字典(假設ID是唯一的),或者一個列表<元組>。但是,不要這樣做,請定義適當的學生類型並返回該列表。 –

+0

@AnthonyPegram你的意思是說公共靜態列表 GetStudents(),而不是公共靜態列表> GetStudent()? –

+0

是的,這是我的建議。 –

回答

0

幾種方法:

  • 創建一個名爲Student有兩個公共屬性idname,然後用List<Student>作爲返回類型的類。

    class Student 
    { 
        public int id {get;set;} 
        public string name {get;set;} 
    } 
    
    public List<Student> GetStudents()... 
    
  • 使用Tuple<int, string>

    public List<Tuple<int, string>> GetStudents()... 
    
  • 使用新的C#是允許寫入返回類型,如(int, string)語法。

    public List<(int id, string name)> GetStudents()... //works in C# 7 
    
  • 使用Dictionary<int, string>作爲返回類型。

    public Dictionary<int, string> GetStudents()... //IDs must be unique 
    
+0

我不確定3在這種情況下適用 - 你如何使用它來返回一個List <(int,string)>? –

+0

@DStanley:沒有嘗試過,但我認爲'(int,string)'只是'Tuple '的簡寫。 – dotNET

+0

從概念上講,它很相似,但我認爲你可以用'List <(int,string)>'替換'List >'。 –

相關問題