Alex
Alex

Reputation: 2959

How to replace null by "NULL" in a List<string> without foreach loop?

I'd like to replace all null value in my List<string> but if don't want to do a foreach loop.

List<string> tmpList = new List<string>();
//src is a List<string> where I want to remplace the null by "NULL"
foreach(string s in src) 
{  
    if(s == null) 
    {
        tmpList.Add("NULL");
    }
    else

    {
        tmpList.Add(s);
    }
}
src = tmpList;

Do you know a better way to do this ? With LINQ may be ?

Upvotes: 1

Views: 6771

Answers (2)

ken2k
ken2k

Reputation: 48975

var list = new List<string>() { null, "test1", "test2" };
for (int i = 0; i < list.Count; i++)
{
    if (list[i] == null)
    {
        list[i] = "NULL";
    }
}

No foreach.


EDIT:

As no one seems to understand the meaning of this answer: LINQ does a foreach loop internally. You want to conditionally modify each item of a list? Then you have to enumerate it.

LINQ is here to help us write queries. Oh wait, this is the Q of LINQ.

LINQ is NOT here to modify existing lists. Just use a good old for loop here. You could of course create a new list based on the existing one with modified values (see best-voted answer), but I'm afraid you'll start using LINQ in a wrong way.

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8894

src.Select(s => s ?? "NULL").ToList();

But what's wrong with using a foreach loop?

Upvotes: 12

Related Questions