我需要在字典中实现两个键并且有点卡住了。我不确定它是否可行,但我的标准是使用两个键来匹配字典数据结构中的搜索选项,类似于下面的Linq:
if(id > 0 && status != null)
{
var result = (from c in db.Employees
where c.EmployeeId == id && c.Status == status
select c).ToList();
}
使用词典,我尝试了以下内容:
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public string Status { get; set; }
}
public class TwoKeyDictionary<k1, k2, T> : Dictionary<k2, Dictionary<k2, T>>
{
}
最后尝试将Employee类与数据绑定并使用List&lt;&gt;为此:
List<Employee> employees = new List<Employee>()
{
new Employee { EmployeeId = 1001, EmployeeName = "John", Address = "On Earth", Status = "Active"},
new Employee { EmployeeId = 1002, EmployeeName = "Jack", Address = "On Earth", Status = "Active"},
new Employee { EmployeeId = 1003, EmployeeName = "James", Address = "On Earth", Status = "Inactive"},
new Employee { EmployeeId = 1004, EmployeeName = "Oswald", Address = "On Earth", Status = "Inactive"}
};
int id = 0;
string status = ""
if (id > 0 && status != "")
{
id = Convert.ToInt32(Console.ReadLine())
status = Console.ReadLine().ToUpper();
}
TwoKeyDictionary<int, string, List<Employee>> dict =
employees.GroupBy(c => new {
CustomerId = c.EmployeeId,
c.Status })
.ToDictionary(g => g.Key.CustomerId, g => g.Key.Status, g => g.ToList());
foreach (var item in dict[id][status])
{
Console.WriteLine(item.CustomerId + " " + item.CustomerName);
}
它看起来已经完成但是现在,我有例外,其中一个是:&#39; 无法转换为lambda表达式以键入System.Collections.Generic.IEComparer,因为它不是委托类型&#39; - ToDictionary(g =&gt; g.Key.CustomerId,g =&gt; g.Key.Status, g =&gt; g.ToList()。此行中的其他错误:var item in dict [id] [状态]。有没有办法摆脱它,可能在某处做错了。
答案 0 :(得分:3)
我会将你的字典更改为:
Dictionary<Tuple<int, string>, List<Employee>>
因为你希望int和string都在一起并指定一个键。
此外,.ToDictionary
调用如下所示:
Dictionary<Tuple<int, string>, List<Employee>> dict =
employees.ToDictionary(g =>
new Tuple<int, string>(g.Key.CustomerId, g.Key.Status), g => g);
答案 1 :(得分:1)
为什么不使用tuple
作为密钥?
Dictionary<Tuple<K1, K2>, V> d1;
答案 2 :(得分:0)
实际上你可以在没有额外课程的情况下完成这项课程,甚至只限于两个课程。使用匿名类型作为键的Lookup<TKey, TElement>
:
var idStatusLookup = employees.ToLookup(x => new {x.EmployeeId, x.Status});
var matchingEmployees = idStatusLookup[new { EmployeeId = 1001, Status = "Active"}];
foreach (Employee emp in matchingEmployees)
{
Console.WriteLine(emp.EmployeeId + " " + emp.EmployeeName);
}
查找类似于字典,但它允许有多个键,并且总是有一个值,即使对于非包含的键也是如此。怎么可能?如果未包含密钥,则返回Enumerable.Empty<TValue>
,并返回相同密钥的值序列。