-1

So I was wondering if there's a way to add a string to a null or empty index in array list. So the thing that I want is that if the array list index is null or empty then I want it to be replaced by another text.

string[] namelist = new string[4] { "dodo", "klee", "diluc", null };
for (int i = 0; i < namelist.Count(); i++)
{
    if (namelist[i] == null)
    {
        *Replace Null Text*
    }
    else
        Console.WriteLine("Taken");
}

Thanks.

8
  • 3
    namelist[i] = "Whatever text you like" Commented Aug 5, 2021 at 10:41
  • 2
    Also, use namelist.Length rather than namelist.Count() -- it's slightly cheaper Commented Aug 5, 2021 at 10:42
  • 1
    Does this answer your question? How do I replace an item in a string array? Commented Aug 5, 2021 at 10:47
  • 1
    This question is basically: How to update arrays, which is a basic topic covered from all tutorials. Commented Aug 5, 2021 at 10:50
  • 1
    @canton7: it really does't matter whether you use Length or Count(). This method is called only once and it checks if the source implements ICollection<T> which is true for arrays, so it's using the arrays Count property (yes, arrays have it, it's simply using Length) instead of enumerating it. Commented Aug 5, 2021 at 10:59

2 Answers 2

1

You're using an array and so Count() doesn't apply, but it would for a collection type like List.

    string[] namelist = new string[4] { "dodo", "klee", "diluc", null };
    for (int i = 0; i < namelist.Length; i++)
    {
        if (string.IsNullOrEmpty(namelist[i]))
        {
            namelist[i] = "filled";
        }
        else
            Console.WriteLine("Taken");
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Enumerable.Count() works on arrays, as well as any other IEnumerable<T>. It's slightly less efficient here, but still works.
-1

It's sometimes a good idea not to modify the array, but instead create a new one.

Here's the easy way:

namelist = namelist.Select(x => x ?? "*Replace Null Text*").ToArray();

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.