2009-11-05 47 views
3

我創建了一個名爲employees的類來存放員工信息。這個班級看起來如下。C中的數組列表#

class Employee 
{ 
    private int employeeID; 
    private string firstName; 
    private string lastName; 
    private bool eligibleOT; 
    private int positionID; 
    private string positionName; 
    private ArrayList arrPhone; 
    private ArrayList arrSector; 

正如你所看到的,我已經創建了一個名爲arrSector的數組。它採用員工所關聯的部門的名稱。現在我也想把部門名稱和部門名稱一起加入。

我的問題是我如何實現扇區id以及單個數組列表變量中的扇區名稱。
我想一起存儲扇區ID和扇區名稱的值。 任何幫助表示讚賞。

回答

0

不太確定你的意思。我認爲你應該實現一個Sector類,也可能使用通用列表。

class Employee 
{ 
    // field 
    private List<Sector> sectors; 
    // property to get the sectors 
    public List<Sector> Sectors { get { return this.sector; } 
} 

// sector class 
class Sector 
{ 
    int Id { get; set; } 
    string Name { get; set; } 
} 
3

您可能需要使用一個字典,而不是一個ArrayList的,但如果你必須使用一個ArrayList,我會創建一個同時擁有扇區ID和SectorName類或結構。

與字典:

Dictionary<int, string> dictSector = new Dictionary<int, string>(); 
dictSector.Add(1,"MySectorName"); 
dictSector.Add(2,"Foo"); 
dictSector.Add(3,"Bar"); 

有了一個ArrayList:

class Sector { 
    public int Id {set; get;} 
    public string Name {set; get;} 
} 

ArrayList arrSectors = new ArrayList(); 
arrSectors.Add(new Sector() {Id = 1, Name = "MySectorName"}); 
arrSectors.Add(new Sector() {Id = 2, Name = "Foo"}); 
arrSectors.Add(new Sector() {Id = 3, Name = "Bar"}); 
5

首先:不要使用ArrayList如果你能幫助它,至少如果你使用.NET 2或更高版本。您可以使用通用的List<T>,這是您放入其中的類型所特有的,這可以爲您節省大量的鑄件。

至於你的問題,你可能想要一個HashtableDictionary<TKey, TValue>。散列表是將一個值()與其他值()關聯的集合。在你的情況下,你可能會有一個整數或一個GUID作爲鍵和一個字符串作爲值。

但正如其他人已經指出,你也可以創建一個Sector類,它主要由ID和名字組成,並將該類的實例放入列表中。

在使用散列表/字典時,您在此獲得的是您可以通過ID快速查找。當你在一個列表中搜索一個特定的ID時,你將不得不遍歷整個列表(當然,如果它被排序,你可以使用二進制搜索),而散列表通常只需要一次查找。

14

創建一個對象來保存這兩條信息。

public class Sector 
{ 
    public string Name { get; set; } 
    public int Id { get; set; } 
} 

然後使用泛型List而不是ArrayList。

class Employee 
{ 
    private int employeeID; 
    private string firstName; 
    private string lastName; 
    private bool eligibleOT; 
    private int positionID; 
    private string positionName; 
    private ArrayList arrPhone; 
    private List<Sector> arrSector; 
} 
+4

絕對是這樣做的方式。當你在它的時候,你可能會建議他把arrPhone改成一個'List '(或'List ',這取決於數字的存儲方式)。 – 2009-11-05 15:20:23

+0

@丹:是的,這是真的,但我不想超出特定問題的範圍。 – 2009-11-05 15:21:35

0
class Sector 
{ 
    int id; 
    string name; 
} 


class Employee 
{ 
    ... 
    List<Sector> sectors; 
} 
0

定義一個新的行業類:

public class Sector 
{ 
    public int Id { get; set; } 

    public string Name { get; set; } 
} 

然後定義列表作爲List<Sector>這樣的:

private List<Sector> sectors; 
-1

如果你的部門有2個值(ID和名稱),猜你(sh)可以:

  1. 創建一個類(內部,公共,您的呼叫)來保存這些值。
  2. 創建一個結構體,看它here
  3. 使用一個KeyValuePair,它將保存這兩個信息,但這是跛腳。

所有其他答案都很好,特別是在建議您使用通用列表時。

+0

非常不同意KeyValuePairs是一個蹩腳的解決方案,因爲這將使字典跛腳的解決方案,它絕不是 – 2009-11-05 18:00:38