【问题标题】:Dictionary with two keys and one value without hashing具有两个键和一个值的字典,没有散列
【发布时间】:2018-06-30 10:44:02
【问题描述】:

我正在寻找一种更好的方法来执行以下操作。

using System;
using System.Collections;

Dictionary<int, string> namebyID = new Dictionary<int, string>();
Dictionary<string, int> idbyName = new Dictionary<string, int>();
Dictionary<string, string> valuebyName = new Dictionary<string, string>(); // users favorite dessert

/* Lets store information about "leethaxor" */
namebyID.Add(1234, "leethaxor");
idbyName.Add("leethaxor", 1234);
valuebyName.Add("leethaxor", "cake");

/* use case 1, I'm given an ID and i need the user's favorite dessert*/
if (namebyID.ContainsKey(1234))
{
    string username;
    namebyID.TryGetValue(1234, out username);
    if (valuebyName.ContainsKey(username))
    {
        string dessert;
        valuebyName.TryGetValue(username, out dessert);
        Console.Write("ID 1234 has a username of " + username + " and loves " + dessert + "\n");
    }
}

/* use case 2, I'm given a username and need to make sure they have a valid ID*/
if (idbyName.ContainsKey("leethaxor"))
{
    int id;
    idbyName.TryGetValue("leethaxor", out id);
    Console.Write("username leethaxor has a valid ID of " + id + "\n");
}

我真的不想使用 3 个不同的字典,因为 idusernamevalue 都是相互关联的。将 key1(id)key2(username) 散列在一起是行不通的,因为我只能得到其中一个,而不是两者。

【问题讨论】:

  • 然后你应该创建一个包含所有这些相关信息的类。
  • 请解释一下“更好的方法”中的“这个”是什么。让帮助变得更容易
  • 这是您之前发布的同一个问题吗? stackoverflow.com/questions/48369716/…
  • @DavidG 似乎是相同的上下文,但显然 OP 已经使用了在该问题中向他/她建议的解决方案。所以这根本不是重复的。
  • 为什么同时使用 ContainsKey 和 TryGetValue?

标签: c# dictionary key


【解决方案1】:

为什么不只使用一个类?此外,使用 TryGetValue() 代替 ContainsKey()。 What is more efficient: Dictionary TryGetValue or ContainsKey+Item?

public class User 
{
    public int Id;
    public string Name;
    public string Value;
}

Dictionary<int, User> userById = new Dictionary<int, User>();

【讨论】:

    【解决方案2】:

    您绝对应该使用自己的类来保存所有属于一起的信息。依赖不同的字典是一团糟,而且您在这些字典中输入的信息越多,就会变得越来越复杂。

    因此,在您的情况下,您可以创建一个类,我们称之为Person。每个Person 都有一个Id、一个UserName 和一个Value

    class Person
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Value { get; set; }
    }
    

    现在创建这些人的列表,例如:

    var list = new List<Person> { 
        new Person { Id = 1234, UserName = "leethaxor", Value = "Cake" },
        new Person { Id = 2, UserName = "Berta", Value = "AnotherValue" }
    };
    

    现在您可以使用给定的Id 或给定的UserName 获取person

    var aPerson = list.FirstOrDefault(x => x.Id = 1234);
    

    var aPerson = list.FirstOrDefault(x => x.UserName = "leethaxor");
    

    您绝对应该了解面向对象编程的基础知识,这是关于对象及其行为的。

    【讨论】:

    • 请注意,使用 LINQ 通过 ID 或名称查找用户通常比使用字典的键执行得慢。但目前尚不清楚性能是否是 OP 关注的问题。
    • @NightOwl888 公平点。但是 OP 仍然可以将实例添加到字典中。创建一个类与此无关,仅与如何检索这些实例有关。
    猜你喜欢
    • 2015-12-22
    • 2019-09-02
    • 2019-07-02
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2018-03-10
    相关资源
    最近更新 更多