I've a requirement to implement two keys in a dictionary and stuck a bit. I am not sure if it's possible to do but my criteria is to make a search option using two keys to match in a dictionary data structure similar to the below Linq:
if(id > 0 && status != null) { var result = (from c in db.Employees where c.EmployeeId == id && c.Status == status select c).ToList(); } With Dictionary, I've tried the following:
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>> { } Finally tried to the bind the Employee class with data and used List<> for that:
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); } It looks completed but right now, I am having exceptions and the one is: 'Cannot convert to lambda expression to type System.Collections.Generic.IEComparer because it is not a delegate type' - ToDictionary(g => g.Key.CustomerId, g => g.Key.Status, g => g.ToList(). The other error in this line: var item in dict[id][status]. Is there any way to get rid of it and may be doing the wrong thing somewhere.
ToDictionaryreturn aDictionary. You can't expect it to automagically return aTwoKeyDictionary.