【发布时间】:2018-03-10 05:51:16
【问题描述】:
我需要在字典中实现两个键,但有点卡住了。我不确定是否可以这样做,但我的标准是使用两个键在类似于以下 Linq 的字典数据结构中匹配一个搜索选项:
if(id > 0 && status != null)
{
var result = (from c in db.Employees
where c.EmployeeId == id && c.Status == status
select c).ToList();
}
使用 Dictionary,我尝试了以下方法:
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:
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);
}
它看起来已完成,但现在,我遇到了异常,其中一个是:'无法将 lambda 表达式转换为 System.Collections.Generic.IEComparer 类型,因为它不是委托类型' - ToDictionary(g => g.Key.CustomerId, g => g.Key.Status, g => g.ToList()。此行中的另一个错误:dict中的var item [id][status]。有没有办法摆脱它,并且可能在某处做错事。
【问题讨论】:
-
List
>怎么样? -
ToDictionary返回Dictionary。你不能指望它会自动返回TwoKeyDictionary。
标签: c# asp.net dictionary data-structures