c# - List.Distinct() causes my parameter to act like a value type -


i have simple list of integers called numbers. send list 2 methods: first uses random fill list 333 numbers between 1 , 100. @ end of filling i'm using 'distinct()' on list distinct random numbers, , prints out amount of items list has. second method receive list , prints out number of elements in also, 'count' property.

how i'm working on same list time , different results?

this code:

class program     {          static list<int> numbers = new list<int>();         static random rnd = new random();          static void main(string[] args)         {             fillnumbers(numbers);             countnumbers(numbers);             console.readline();         }          private static void countnumbers(list<int> numbers)         {             console.writeline("there {0} numbers list", numbers.count);         }          private static void fillnumbers(list<int> numbers)         {             (int = 0; < 333; i++)             {                 int n = rnd.next(1, 101);                 numbers.add(n);                          }             numbers = numbers.distinct().tolist();             console.writeline("after distinct there {0} numbers in list",numbers.count);         }     } 

this line:

numbers = numbers.distinct().tolist(); 

is creating new list. list contain distinct values, original list not. calling reference fix it:

    private static void fillnumbers(ref list<int> numbers)     {         (int = 0; < 333; i++)         {             int n = rnd.next(1, 101);             numbers.add(n);                      }         numbers = numbers.distinct().tolist();         console.writeline("after distinct there {0} numbers in list",numbers.count);     } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -