简体   繁体   English

在C#中如何在字符串列表中传递string.empty

[英]In C # how to pass string.empty in a list of string

i have a list of string 我有一个字符串列表

Emails = new List<string>() { "R.Dun@domain.co.nz", "S.Dun@domain.co.nz" }

now i want to pass string.empty to first value of list 现在我想将string.empty传递给list的第一个值

something like 就像是

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

how to put a loop for eg for each value of list do something. 如何为例如list的每个值设置循环以执行某些操作。

您可以将第一个元素直接设置为string.Empty:

policy.Emails[0]=string.Empty;

You can use indexof function for finding a string in the list as below, 您可以使用indexof函数在列表中查找字符串,如下所示,

List<string> strList = new List<string>() { "R.Dun@domain.co.nz", "S.Dun@domain.co.nz" };

int fIndex = strList.IndexOf("R.Dun@domain.co.nz");

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, 或者,如果您想将第一个项目替换为string.Empty,那么正如dasblinkenlight所述,您可以直接使用索引,

strList[0] = string.Empty

Hope it helps. 希望能帮助到你。

You can prepend string.Empty to an existing list with concat: 您可以在string之前添加string.Empty到concat的现有列表中:

var emails = new List<string> {"R.Dun@domain.co.nz", "S.Dun@domain.co.nz"};
policy.Emails = new[] {string.Empty}.Concat(emails).ToList();

Now policy.Emails looks like this: 现在policy.Emails看起来像这样:

{"", "R.Dun@domain.co.nz", "S.Dun@domain.co.nz"}

If you would like to replace the first item, use Skip(1) before concatenating: 如果要替换第一项,请在连接前使用Skip(1)

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

To generalize, replacing the initial n values with empty strings would look like this: 概括地说,用空字符串替换初始n值将如下所示:

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;

如果要在列表的开头添加空字符串,可以执行以下操作:

emails.Insert(0, string.Empty);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM