Hudlommen Hudlommen - 3 months ago 7
C# Question

variable changes to list<T>

So i am new to c# and have therefore never really used list before. I've gotten many good things out of it so far, but i've hit one snag.

public static List<player> data(string ply, int val)
{
string rtn = "-";
List<player> playerdata = new List<player>()
{
new player() { plr = "player1", name = "pl A", one = 0, two = 0, twopair = 0 },
new player() { plr = "player2", name = "pl B", one = 0, two = 0, twopair = 1 }
};

var game = playerdata.Where(p => p.plr == ply);

foreach (var player in game)
{
player.one = val; //This is where my problem is
rtn = player.name;
}
return playerdata;
}


So under foreach, with the player.et = val; .. That works fine. But i would really like to be able to have "player.et" as a dynamic input. So i could send

data(string ply, int val, SOMETHING HERE)


linked to

foreach (var player in game)
{
SOMETHING HERE = val;
rtn = player.name;
}


How do i do that?

Thanks, in advance :D

Answer

Is this what you want?

public static List<player> data(string ply, string property, int val)
{
    string rtn = "-";

    List<player> playerdata = new List<player>()
    {
        new player() { plr = "player1", name = "pl A", one = 0, two = 0, twopair = 0 },
        new player() { plr = "player2", name = "pl B", one = 0, two = 0, twopair = 1 }
    };

    playerdata.Where(p => p.plr == ply).ToList().ForEach(p => {
        var propInfo = p.GetType().GetProperty(property);
        if (propInfo != null)
            propInfo.SetValue(p, val, null);
        rtn = p.name;
    });

    return playerdata;
}
Comments