c# - Separate functions without duplicating code -


i working on program traverse through list of numbers 2 different functions find sum , specific value. here code have implemented

class program {     static int i, sum;     static list<int> store = new list<int>();      static void main(string[] args)     {           (i = 0; < 100; i++)         {             store.add(i);         }          = 0;         traverselist();         console.readline();     }      static void traverselist()     {         while (i < store.count)         {             findvalue();             findsum();             i++;         }          console.writeline("the sum {0}", sum);     }      static void findvalue()     {                    if (store[i] == 40)         {             console.writeline("value 40");         }                     }      static void findsum()     {         sum = sum + store[i];     } } 

i thinking of separating findsum , findvalue 2 different functions , not calling them in traverselist. there other way of doing rather duplicating common code of list traversal in 2 functions have done here

class program {     static int i, sum;     static list<int> store = new list<int>();      static void main(string[] args)     {           (i = 0; < 100; i++)         {             store.add(i);         }          = 0;         findvalue();         = 0;         findsum();          console.readline();     }      static void findvalue()     {         while (i < store.count)         {             if (store[i] == 40)             {                 console.writeline("value 40");             }             i++;         }     }      static void findsum()     {         while (i < store.count)         {             sum = sum + store[i];             i++;         }          console.writeline("the sum {0}", sum);     } } 

to find sum of series of numbers can use simple linq function:

list<int> numbers = new list<int>(); int sum = numbers.sum(); 

i not sure mean find value. if want check if 1 of numbers in series equal value can use linq function any:

int myvalue = 40; bool hasmyvalue = numbers.any(i => == myvalue); 

this uses lambda expression executes function , passes each element in collection function. function returns true or false indicate element match any test.

if instead want check how many numbers in sequence match value can instead use count function so:

int numberofmatches = numbers.count(i => == myvalue); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -