I am trying to work with Dictionary<>
along with List<>
for searching purpose. I know, I can do this easily with List<>
as follows:
var con = (from c in db.Customers
where c.Status == status
select c).ToList();
But preferred and tried to implement the above with Dictionary<>
. My concept (We all know that) is using the key/value will increase the search option performance. This looks simple and stuck a bit. Here what I've tried:
static void Main(string[] args)
{
Dictionary<string, Customer> custDictionary = new Dictionary<string, Customer>(); //Dictionary declared
List<Customer> lst = new List<Customer>(); //List of objects declared
Customer aCustomer = new Customer(); //Customer object created
/**Assign values - Starts**/
aCustomer.CustomerId = 1001;
aCustomer.CustomerName = "John";
aCustomer.Address = "On Earth";
aCustomer.Status = "Active";
aCustomer.CustomerId = 1002;
aCustomer.CustomerName = "James";
aCustomer.Address = "On Earth";
aCustomer.Status = "Inactive";
/**Assign values - Ends**/
custDictionary.Add(aCustomer.Status, aCustomer); //Added to the dictionary with key and value
string status = Console.ReadLine().ToUpper();
if (custDictionary.ContainsKey(status)) //If key found in the dictionary
{
Customer cust = custDictionary[status];
Console.WriteLine(cust.CustomerId + " " + cust.CustomerName); //Outputs the final result - Right now no result found here
}
Console.ReadKey();
}
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Address { get; set; }
public string Status { get; set; }
}
Unfortunately, the above doesn't return any result. What I am trying is to get customer details by passing status key and again passed Customer
object as the value. I am not sure what I am missing here.
One more thing, in real-life projects, we get database results as list. So in this scenario, if Dictionary<>
is used, I believe, the database results should be kept as follows:
lst.Add(aCustomer); //As database will have more result or data simply
On the other hand, I believe, the dictionary should look like the below:
Dictionary<string, List<Customer>> custDictionary = new Dictionary<string, List<Customer>>();
My question - Is it a good idea to pass a list of objects in the dictionary for the key/vale pair and I've tried using so. But didn't get the output yet.
Note: This sounds like a novice question and yes, it's. I've tried to search online and still studying it. I apology to ask such a question and would expect some answers if there are any better ways to do the above.