1

i have a list of string

Emails = new List<string>() { "[email protected]", "[email protected]" }

now i want to pass string.empty to first value of list

something like

policy.Emails = new List<string>(){string.Empty};

how to put a loop for e.g. for each value of list do something.

4 Answers 4

1

you can directly set the first element as string.Empty:

policy.Emails[0]=string.Empty;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use indexof function for finding a string in the list as below,

List<string> strList = new List<string>() { "[email protected]", "[email protected]" };

int fIndex = strList.IndexOf("[email protected]");

if(fIndex != -1)
    strList[fIndex] = string.Empty;

Or if you want to replace first item with string.Empty then as dasblinkenlight mentioned you can do using the index directly,

strList[0] = string.Empty

Hope it helps.

Comments

0

You can prepend string.Empty to an existing list with concat:

var emails = new List<string> {"[email protected]", "[email protected]"};
policy.Emails = new[] {string.Empty}.Concat(emails).ToList();

Now policy.Emails looks like this:

{"", "[email protected]", "[email protected]"}

If you would like to replace the first item, use Skip(1) before concatenating:

policy.Emails = new[] {string.Empty}.Concat(emails.Skip(1)).ToList();

To generalize, replacing the initial n values with empty strings would look like this:

policy.Emails = Enumerable.Repeat(string.Empty, 1).Concat(emails.Skip(n)).ToList();

Note: It goes without saying that if you do not mind modifying the list in place, the simplest solution is to do

emails[0] = string.Empty;

3 Comments

thanks, how can i replace [email protected] with a empty string ?
@shab Do you want to replace "[email protected]" because it is the first item on the list?
yes i want to replace the first item with an empty string
-1

If you want to add an empty string at the beginning of a list you could do:

emails.Insert(0, string.Empty);

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.