0

I've following array of strings. Default value of each string is set to string.Empty. And this array is returned by a fuction. Now, I want to print only those indexes that are not null. I can use if-else for each index but it could be very long way for going through 8 items. is there any short way so that I can print only those items that are not nulll

string [] muniSearches = {airSearchReport, certOfOccupancy, emerRepair, fire, fZone,foSearch, health, hsVoilation};
2
  • I tried by conventional if-else Commented Jun 20, 2016 at 12:01
  • a for loop for 8 items is not long ! :P Commented Jun 20, 2016 at 12:07

3 Answers 3

4

You could use Select and return the provided index if the value is null:

var indexesNotNull = muniSearches.Select((v, i) => new { Value = v, Index = i })
                                 .Where(x => x.Value != null)
                                 .Select(x => x.Index);

Or simply using a for loop:

List<int> indexesNotNull = new List<int>();
for (int index = 0; index < muniSearches.Length; index++)
{
    if (muniSearches[index] != null)
    {
        indexesNotNull.Add(index);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I suggest to use !string.IsNullEmpty(muniSearches[index]) as the OP said something like the strings might be initialized as string.empty.
If an empty string is the default, and OP wants to know the null's, this is the answer that fits the question. If the question is different, you might be right.
Tbh, i think OP is mixing up null and string.Empty ;)
That is certainly possible. That is why you should keep your comment @lokusking
1

I wasn't clear whether you wanted values or indexes. If you want values and you can use linq in the context, that's fairly straight forward.

muniSearches
.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.ForEach(Console.WriteLine);

If you want indexes, that's again doable but a little more involed. Something like:

muniSearches
.Select((s, i) => new {value = s, index = i})
.Where(o => !string.IsNullOrEmpty(o.value))
.Select(o => o.index)
.ToList()
.ForEach(Console.WriteLine);

2 Comments

Where do you provide the index, as OP asked?
Wasn't clear about that, updated with a second option.
0

You can check the length of that string using lambda expressions syntax and then store the index of the string having any data in that.

var Indexes = muniSearches.Select((Value, Index) => new { Value , Index })
                             .Where(x => x.Value.Length > 0)
                             .Select(x => x.Index);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.