Reference type List<T> with order by -
i have weird situation, can't explain, can me understand it? understanding, list reference type, mean after change list inside function rating, list changed outside function. in real doesn't change after sorting. there problem misunderstand?
class program { static void main(string[] args) { list<user> data = new list<user> { new user { totalscore = 0 }, new user { totalscore = 3 }, new user { totalscore = 4 } }; rating(data); //list data doesnt order descending totalscore } private static void rating(list<user> data) { data = data.orderbydescending(e => e.totalscore).tolist(); } } public class user { public int id { get; set; } public decimal totalscore { get; set; } }
list reference type, should not confuse passing argument reference function. default, function arguments in c# passed value. passing data
reference value rating
, data
variable in function copy of reference in caller. allows function mutate same list through reference, assignments affect local variable.
to pass variable reference need use ref
keyword:
private static void rating(ref list<user> data) { data = data.orderbydescending(e => e.totalscore).tolist(); }
and change call to:
rating(ref data);
Comments
Post a Comment