所以我有一个清单:
["item1"]
["item2"]
["item3"]
Run Code Online (Sandbox Code Playgroud)
我希望列表是这样的:
[""]
["item1"]
[""]
["item2"]
[""]
["item3"]
Run Code Online (Sandbox Code Playgroud)
一个简单的从后到前循环给我这样的:
for (int i = list.Count-1; i >= 0; i--)
list.Insert(i, string.Empty);
Run Code Online (Sandbox Code Playgroud)
但我想知道LINQ是否有更优雅的方法来做到这一点?
mih*_*hai 13
您可以使用Intersperse
扩展方法.这样,意思很清楚,代码可以重复使用.从Enumerable.Intersperse的Extension方法获取的代码稍作修改,在第一个位置也包含一个空字符串.
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
foreach (T value in source)
{
yield return element;
yield return value;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种方法:
list = list.SelectMany(x => new [] { string.Empty, x }).ToList();
Run Code Online (Sandbox Code Playgroud)
但值得注意的是,这会创建不必要的数组.如果您的列表足够大,可能会出现问题.相反,我会创建一个具有容量的新列表,并使用循环填充它:
var newList = new List<string>(list.Count * 2);
int j = 0;
for(int i = 0; i < list.Count * 2; i++)
newList.Add(i % 2 == 0 ? string.Empty : list[j++]);
Run Code Online (Sandbox Code Playgroud)
这样可以避免每次添加或插入项目时调整列表大小.
归档时间: |
|
查看次数: |
1301 次 |
最近记录: |