2009-11-05 97 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