0

Sorry im newb and I don't know how to ask my question properly in the title. I have a database:

class PlayerData
    {
        public ulong id;
        public string name;
        public int kills;
        public int deaths;
    }

and I want to return the value corresponding to the requested key

object getStats(ulong uid, string stat)
    {
        var player = BasePlayer.FindByID(uid);
        PlayerData data = PlayerData.Find(player);

        object value = data.TryGetValue(stat); // I know this ain't right

        return value;
    }

example:

int kills = getStats(123456, kills); //will ask for the value of "kills" in the data. Return data.kills

stat could be anything in data (id, name, kills, deaths)

thanks alot!

  • Does [something like this help](https://stackoverflow.com/a/2566177/1790644)? – Matt Clark Jun 07 '18 at 23:11
  • How about using switch. For example object TryGetValue(string stat) { object returnValue=null; switch(stat) { case "name": returnValue=name; break; case "kills": returnValue=kill; break; } return returnValue; } – Sun Maung Oo Jun 07 '18 at 23:16

2 Answers2

0

You could take Sun Maung Oo's suggestion of using a switch statement:

object TryGetValue(int playerId, string name)
{
    var player = GetPlayer(playerId);
    switch (name)
    {
        case "name": return name;
        case "kills": return kills;

        // Other properties
        // ...

        default: return null;
    }
}

Or you could flatten the data:

public class Statistic
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
    public object Value { get; set; }
}

Then finding the value is a matter of finding the statistic with the given player id and name.

Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
0

I suppose what you are trying to do here is to get the object value base on the object Name? If that is the case, I think you could use reflection to achieve that. You could reference this answer: Get property value from string using reflection in C#

Sample Code:

class PlayerData
{
    public ulong id;
    public string name;
    public int kills;
    public int deaths;
}

object getStats(ulong uid, string stat)
{
    var player = BasePlayer.FindByID(uid);
    PlayerData data = PlayerData.Find(player);

    object value = data.GetType().GetProperty(stat).GetValue(data, null);

    return value;
}
josh hua
  • 51
  • 4