关于c#:使用字典键/值对实现对象列表

Implement List of Objects Using Dictionary Key/Value Pair

我正试图与Dictionary<>List<>一起工作,以便进行搜索。我知道,用List<>我可以很容易地做到这一点,如下所示:

1
2
3
var con = (from c in db.Customers
           where c.Status == status
           select c).ToList();

但更倾向于并试图用Dictionary<>来实现上述目标。我的概念(我们都知道)是使用键/值将提高搜索选项的性能。这看起来很简单,有点卡住了。以下是我的尝试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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<>,我认为数据库结果应该保持如下:

1
lst.Add(aCustomer); //As database will have more result or data simply

另一方面,我认为字典应该如下所示:

1
Dictionary<string, List<Customer>> custDictionary = new Dictionary<string, List<Customer>>();

我的问题是,在字典中为key/vale对传递一个对象列表是个好主意吗?我已经尝试过这样做。但是还没有得到输出。

注意:这听起来像是一个新手的问题,是的。我试过在网上搜索,但仍然在学习。我很抱歉问这样一个问题,如果有更好的方法来做以上的话,我希望能得到一些答案。


更新

如果要将它们存储在列表中,可以执行以下代码。要选择项目,可以使用LINQ,这样字典中就没有重复值的问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
        var lst = new List<Customer>(); //List of objects declared

        lst.AddRange(
            new List<Customer>() {
                new Customer()
                {
                    CustomerId = 1001,
                    CustomerName ="John",
                    Address ="On Earth",
                    Status ="Active"
                },
                new Customer()
                {
                    CustomerId = 1002,
                    CustomerName ="James",
                    Address ="On Earth",
                    Status ="Inactive"
                }
            }
        );

        var status = Console.ReadLine();
        var selected = lst.Where(x => x.Status.ToUpper() == status.ToUpper()).ToList();
        foreach (var item in selected)
        {
            Console.WriteLine(item.CustomerId +"" + item.CustomerName);
        }

更新2

如果要将上述列表添加到字典中,可以执行以下操作:

1
2
3
4
5
var custDictionary = new Dictionary<string, List<Customer>>();

// the above code for the list

custDictionary.Add("keyname", lst);

原始答案

您只保存一个客户,因为您正在用第二个客户覆盖第一个客户:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Dictionary<string, Customer> custDictionary = new Dictionary<string, Customer>();
List<Customer> lst = new List<Customer>();

// Add first customer
var aCustomer = new Customer()
{
    CustomerId = 1001,
    CustomerName ="John",
    Address ="On Earth",
    Status ="Active"
};
custDictionary.Add(aCustomer.Status.ToUpper(), aCustomer);

// Add second customer
var bCustomer = new Customer()
{
    CustomerId = 1002,
    CustomerName ="James",
    Address ="On Earth",
    Status ="Inactive"
};
custDictionary.Add(bCustomer.Status.ToUpper(), bCustomer);

此外,您还需要将状态存储为大写,因为您正在检查状态是否以大写形式存在:

1
2
3
4
5
6
7
8
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();


如果您已经有了这个列表,并且想要创建一个Dictionary>,那么您可以使用它:

1
2
Dictionary<string, List<Customer>> dict =
        list.GroupBy(c=>c.Status.ToUpper()).ToDictionary(g => g.Key, g=> g.ToList());

并迭代它:

1
2
3
foreach (var customer in dict[status.ToUpper()])
{
}

但是,

我看不出这样做的价值。如果您需要让所有具有特定状态的客户保持现有状态—一个简单的LINQ查询。


您没有得到任何输出,因为您正在将输入转换为大写,而您在pascalcase中插入了键,并且在C集合的情况下,键区分大小写。这样,您的输入与集合中的任何键都不匹配

将您的行号:29更改为此代码

1
 string status = Console.ReadLine();

and insert"Inactive" from you console this key exist in your collection
so you will desired result..


首先,字典键应该是customerid而不是status。检查字典是否包含键是一个很好的实践,否则它将抛出已经添加了相同键的异常。所以最好先检查,然后在字典中执行添加或更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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";
   if (!custDictionary.ContainsKey(aCustomer.CustomerId))
        custDictionary.Add(aCustomer.CustomerId, aCustomer);
    else
        custDictionary[aCustomer.CustomerId] = aCustomer;

   aCustomer.CustomerId = 1002;
   aCustomer.CustomerName ="James";
   aCustomer.Address ="On Earth";
   aCustomer.Status ="Inactive";
   /**Assign values - Ends**/

   if (!custDictionary.ContainsKey(aCustomer.CustomerId))
        custDictionary.Add(aCustomer.CustomerId, aCustomer);
    else
        custDictionary[aCustomer.CustomerId] = aCustomer;


   string status = Console.ReadLine().ToUpper();

   if (custDictionary.ContainsKey(aCustomer.CustomerId)) //If key found in the dictionary
   {
      Customer cust = custDictionary[aCustomer.CustomerId];
      Console.WriteLine(cust.CustomerId +"" + cust.CustomerName); //Outputs the final result - Right now no result found here
   }

  Console.ReadKey();
}


即使添加状态为键,代码也有两个问题。

  • 您需要创建2个对象来创建2个客户,一个接一个。您只添加一次客户,并分配两次值。

  • Console.ReadLine().ToUpper()—删除ToUpper(),因为您是在混合情况下添加值。如果要这样做,请使用StringComparer.InvariantCultureIgnoreCase初始化字典。

  • 这对你有用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    Dictionary<string, Customer> custDictionary = new Dictionary<string, Customer>(StringComparer.InvariantCultureIgnoreCase); //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";
       custDictionary.Add(aCustomer.Status, aCustomer); //Added to the dictionary with key and value

       Customer bCustomer = new Customer(); //Customer object created
       bCustomer.CustomerId = 1002;
       bCustomer.CustomerName ="James";
       bCustomer.Address ="On Earth";
       bCustomer.Status ="Inactive";


       custDictionary.Add(bCustomer.Status, bCustomer); //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.ReadLine();