我正在尝试创建一个多键字典,其中的值是可枚举的。目的是能够使用第一个键执行查找,如果没有匹配项,则可以使用第二个键进行花药查找。
到目前为止,这是我的解决方案:
public class MultipleKeyDictionary<TEmployeeIDKey, TBadgeNumberKey, TValue> : IEnumerable<TValue>
{
private object m_data_lock = new object();
private Dictionary<TBadgeNumberKey, TEmployeeIDKey> badgeNumberDictionary = new Dictionary<TBadgeNumberKey, TEmployeeIDKey>();
private Dictionary<TEmployeeIDKey, TValue> empIDDictionary = new Dictionary<TEmployeeIDKey, TValue>();
public void AddValue(TEmployeeIDKey empIDKey, TBadgeNumberKey badgeKey, TValue value)
{
lock (m_data_lock)
{
badgeNumberDictionary[badgeKey] = empIDKey;
empIDDictionary[empIDKey] = value;
}
}
public TValue getByBadgeNumber(TBadgeNumberKey badgeKey)
{
lock (m_data_lock)
return empIDDictionary[badgeNumberDictionary[badgeKey]];
}
public TValue getByEmployeeID(TEmployeeIDKey empIDKey)
{
lock (m_data_lock)
return empIDDictionary[empIDKey];
}
public bool TryGetValueByEmployeeID(TEmployeeIDKey empIDKey, out TValue value)
{
return empIDDictionary.TryGetValue(empIDKey, out value);
}
public bool TryGetValueByBadgeKey(TBadgeNumberKey badgeNumberKey, out TValue value)
{
value = default(TValue);
if (badgeNumberDictionary.TryGetValue(badgeNumberKey, out TEmployeeIDKey empIDKey))
{
return empIDDictionary.TryGetValue(empIDKey, out value);
}
return false;
}
public IEnumerator<TValue> GetEnumerator()
{
return empIDDictionary.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
问题在于EmployeeID和BadgeNumber或它们两者都可能为空。 如果其中一个键可以为null,如何修改它以便执行所需的查找?
编辑: 这是我用来执行查找的代码,其中gateLogGroups是一组由BadgeNumber和EmployeeID分组的Gate Logs,而invoiceRecords属于MultipleKeyDictionary类 < / p>
foreach (var cardNumberGroup in gateLogGroups)
{
invoiceRecords.TryGetValueByEmployeeID(cardNumberGroup.Key.EmpIDNum, out InvoiceRecord invoiceRecord);
if (invoiceRecord == null)
{
invoiceRecords.TryGetValueByBadgeKey(cardNumberGroup.Key.CardNumber, out invoiceRecord);
if (invoiceRecord == null)
{
exceptions.Add(new GateLogWithNoMatchingInvoiceException(cardNumberGroup.GateLogs.ElementAt(0), invoiceRecords.ElementAt(0).InvoiceHeaderId));
continue;
}
}