【发布时间】:2017-09-26 09:58:55
【问题描述】:
我正在尝试使用 Dictionary<> 和 List<> 进行搜索。我知道,我可以使用List<> 轻松做到这一点,如下所示:
var con = (from c in db.Customers
where c.Status == status
select c).ToList();
但首选并尝试使用Dictionary<> 实现上述功能。我的概念(我们都知道)是使用键/值会提高搜索选项的性能。这看起来很简单并且有点卡住了。这是我尝试过的:
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; }
}
不幸的是,上面没有返回任何结果。我正在尝试通过传递状态键并再次传递Customer 对象作为值来获取客户详细信息。我不确定我在这里缺少什么。
还有一件事,在现实生活中的项目中,我们将数据库结果作为列表。所以在这种场景下,如果使用Dictionary<>,我相信数据库结果应该保持如下:
lst.Add(aCustomer); //As database will have more result or data simply
另一方面,我认为字典应该如下所示:
Dictionary<string, List<Customer>> custDictionary = new Dictionary<string, List<Customer>>();
我的问题 - 在字典中为键/值对传递对象列表是否是个好主意,我已经尝试过使用它。但是还没有得到输出。
注意:这听起来像是一个新手问题,是的。我已经尝试在网上搜索并仍在研究它。我很抱歉提出这样的问题,如果有更好的方法来做上述事情,我会期待一些答案。
【问题讨论】:
-
不应该是您的字典键
CustomerId?您当前正在添加状态。 -
我正在尝试将密钥作为字符串 @krlzlx 传递。这会产生差异吗?
-
如果您有多个具有相同状态的客户,您将收到重复错误。
-
我知道了@krlzlx 并感谢它。
标签: c# asp.net list dictionary