0
我正在研究此培訓視頻。我在下面的例子中注意到,我的代碼每次都會將最後一項留在列表之外。在我使代碼更加花哨和可讀性之前,它工作正常。爲什麼我的代碼在每種情況下都將一個項目從列表中刪除?
問題:爲什麼我的代碼離開最後一個項目?
SortedDictionary<string, SortedSet<Employee>>
代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private void printDictionary(Dictionary<string, List<Employee>> InputDictionaryParm1)
{
foreach (var a in InputDictionaryParm1)
{
Console.WriteLine(a.Key);
foreach (var e in a.Value)
{
Console.WriteLine("\t" + e.Name);
}
}
Console.ReadKey();
}
static void Main(string[] args)
{
var d = new DepartmentCollection();
d.AddDept("AA", new Employee { Name = "L" })
.AddDept("AA", new Employee { Name = "A" });
d.AddDept("BB", new Employee { Name = "D" })
.AddDept("BB", new Employee { Name = "E"})
.AddDept("BB", new Employee { Name = "F"})
.AddDept("BB", new Employee { Name = "A"});
d.AddDept("CC", new Employee { Name = "J" })
.AddDept("CC", new Employee { Name = "Z" })
.AddDept("CC", new Employee { Name = "X" })
.AddDept("CC", new Employee { Name = "Y" });
d.AddDept("DD", new Employee { Name = "T" })
.AddDept("DD", new Employee { Name = "W" })
.AddDept("DD", new Employee { Name = "E" })
.AddDept("DD", new Employee { Name = "A" });
foreach (var a in d)
{
Console.WriteLine(a.Key);
foreach (var e in a.Value)
{
Console.WriteLine("\t" + e.Name);
}
}
Console.ReadKey();
//printDictionary(d);
}
}
public class EmployeeComparer : IEqualityComparer<Employee>,
IComparer<Employee>
{
public EmployeeComparer() { }
public bool Equals(Employee x, Employee y)
{
return String.Equals(x.Name, y.Name);
}
public int GetHashCode(Employee obj)
{
return obj.Name.GetHashCode();
}
public int Compare(Employee x, Employee y)
{
return String.Compare(x.Name, y.Name);
}
}
public class DepartmentCollection : SortedDictionary<string, SortedSet<Employee>>
{
public DepartmentCollection()
{
Console.WriteLine("DepartmentCollection");
}
public DepartmentCollection AddDept(string d, Employee e)
{
if (ContainsKey(d))
{
this[d].Add(e);
}
else
{
Add(d, new SortedSet<Employee>(new EmployeeComparer()));
}
return this;
}
}
}
屏幕截圖:
看起來像一個未接來電,以'這個[d]。新增(E);' – pinkfloydx33
你應該有利於組成繼承。而不是擴展'SortedSet','DepartmentCollection'應該包裝一個'SortedSet'。因爲它揭示了集合的內部,允許在不使用自己的添加方法的情況下操作它,該方法保持集合的某些屬性(即每個內部集合都是非空的)。當您公開所有有關該集的信息時,這些屬性可能會被違反。 – Servy
快速瀏覽會顯示缺少的不是最後一個順序,但第一個添加.. –