我正在制作这个培训视频.我在下面的示例中注意到,我的代码每次都会将最后一项留在列表中.在我使代码更加花哨和可读之前,它工作正常.
问题:为什么我的代码会关闭最后一项?
SortedDictionary<string, SortedSet<Employee>>
Run Code Online (Sandbox Code Playgroud)
码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
屏幕截图:

AddDept如果密钥丢失,您的方法实际上不会添加值:
public DepartmentCollection AddDept(string d, Employee e)
{
if (ContainsKey(d))
{
this[d].Add(e);
}
else
{
Add(d, new SortedSet<Employee>(new EmployeeComparer()));
// Add this!
this[d].Add(e);
}
return this;
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以反转条件以简化此代码:
public DepartmentCollection AddDept(string d, Employee e)
{
if (!ContainsKey(d))
{
Add(d, new SortedSet<Employee>(new EmployeeComparer()));
}
this[d].Add(e);
return this;
}
Run Code Online (Sandbox Code Playgroud)