tags:

views:

63

answers:

2

I have a linq query that returs a list of int. I want to count all the items in the list. then count all the items with number 0 and then remove items with 0 from the list.

please show simple example,mine is a ugly.

+1  A: 

Probably the best method:

List<int> list = GetList();

int countAll = list.Count;
int countZero = list.RemoveAll(i => i == 0);
//RemoveAll returns the number of elements removed = the count of 0es


The naive method:

List<int> list = GetList();

int countAll = list.Count;
int countZero = list.Count(i => i == 0);

//remove zeroes
for(int i = list.Count - 1; i >= 0; i--)
    if(list[i] == 0) list.RemoveAt(i);

The probably-faster-than-that-because-it's-only-one-pass-through method:

List<int> list = GetList();

int countAll = list.Count;
int countZero = 0;

//remove zeroes
for(int i = list.Count - 1; i >= 0; i--)
    if(list[i] == 0) 
    {
        list.RemoveAt(i);
        countZero++;
    }
lc
+2  A: 
IList<int> intList = SomeFunctionThatReturnsInts();

int count = intList.Count();
int zeroCount = intList.Where(v => v == 0).Count();
intList.RemoveAll(v => v == 0);
Eric Petroelje