1

i'm printing all non null values from array which contain null values. i want to print only non null values

string a = "welcome";

var rm = new string [] {null,"hai",null,"15"};

Console.WriteLine("{0}",!String.IsNullOrEmpty(rm[0])? a 
:!String.IsNullOrEmpty(rm[1]) ? a +":"+ rm[1] : 
!String.IsNullOrEmpty(rm[2]) ? a +":"+ rm[1]+ ":"+rm[2] : a +":"+ rm[1]+ 
":"+rm[2]+":"+rm[3] ); 

actual output : welcome:hai

Expected output : welcome:hai:15

Babu
  • 125
  • 3
  • 10

2 Answers2

3

You can get and IEnumerable representing all non-null and non-empty values by using the Where method.

Your array is called rm so you could get the IEnumerable like this:

IEnumerable<string> nonNullNonEmptyValues = rm.Where(e => !String.IsNullOrEmpty(e));

If you want to join them like in your example you can use String.Join like this (@AgentFire has an error in his comment since this method actually takes the separator first, then the values):

String joined = String.Join(":", nonNullNonEmptyValues);
Joelius
  • 3,839
  • 1
  • 16
  • 36
3

If you want using a loop, it will your solution:

string a = "welcome";

var rm = new string [] {null,"hai",null,"15"};
for(int i = 0; i < rm.Length; i++)
{
  if(!string.IsNullOrWhitespace(rm[i])
    a += ":" + rm[i];
}
Console.WriteLine(a);
chesh111re
  • 184
  • 2
  • 11