Search code examples
c#linq

Exclude Zeros From Array of String


I've a list of strings as follows:

A:2
B:2
C:0
D:0

I am trying to exclude the values with zeroes, so expected output should be as follows:

A:2
B:2

I tried something as follows and got an exception as well:

foreach (var item in charCnt.OrderBy(q => q).ToList().RemoveAll(p => p.Contains("0")))
{
    concat += item + ", "; //Concatenate items from the list
}

Exception:

foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public instance or extension definition for 'GetEnumerator'

I know, this seems pretty basic as the statement says. Any way I can rid of the above using simple statement?

Updated 1:

 List<string> charCnt = new List<string> { "A:1", "C:-1", "C:1", "B:1", "B:1", "D:-2" "A:1", "D:2" };

Updated 2: Here's the tried one: Sample Code


Solution

  • Probably you want:

    var orderedList = charCnt.OrderBy(q => q).ToList();
    orderedList.RemoveAll(p => p.Contains("0")); // maybe change "0" to '0' ?
    var concatenedString = string.Join (", ", orderedList);