[英]In C # how to pass string.empty in a list of string
我有一個字符串列表
Emails = new List<string>() { "R.Dun@domain.co.nz", "S.Dun@domain.co.nz" }
現在我想將string.empty
傳遞給list的第一個值
就像是
policy.Emails = new List<string>(){string.Empty};
如何為例如list的每個值設置循環以執行某些操作。
您可以將第一個元素直接設置為string.Empty:
policy.Emails[0]=string.Empty;
您可以使用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;
或者,如果您想將第一個項目替換為string.Empty,那么正如dasblinkenlight所述,您可以直接使用索引,
strList[0] = string.Empty
希望能幫助到你。
您可以在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();
現在policy.Emails
看起來像這樣:
{"", "R.Dun@domain.co.nz", "S.Dun@domain.co.nz"}
如果要替換第一項,請在連接前使用Skip(1)
:
policy.Emails = new[] {string.Empty}.Concat(emails.Skip(1)).ToList();
概括地說,用空字符串替換初始n
值將如下所示:
policy.Emails = Enumerable.Repeat(string.Empty, 1).Concat(emails.Skip(n)).ToList();
注意:不用說,如果您不介意修改列表,最簡單的解決方案是
emails[0] = string.Empty;
如果要在列表的開頭添加空字符串,可以執行以下操作:
emails.Insert(0, string.Empty);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.