c# - 如何在 C# 中复制列表成员?

标签 c# list

int x = 9; 
List<string> list = new List<string> {"a", "b"};

我希望列表为:a b a b a ... until list.Count = x。我怎样才能做到这一点?

最佳答案

您可以使用 LINQ 轻松完成:

List<string> result = (from ignored in Enumerable.Range(0, int.MaxValue)
                       from item in list
                       select item).Take(count).ToList();

或者不使用查询表达式:

List<string> result = Enumerable.Range(0, int.MaxValue)
                                .SelectMany(ignored => list)
                                .Take(count)
                                .ToList();

这里使用 Enumerable.Range 只是为了强制重复 - 就像 Ani 使用 Enumerable.Repeat 的方法一样,当然也可以。

关于c# - 如何在 C# 中复制列表成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10909370/

相关文章:

C# 备份和恢复剪贴板

c# - 设置窗口位置

c# - 使用 linq foreach 更新 2 个字段

c# - yield 返回 vs Lazy<T>

python - 按值对元组排序,当值相等时使用列表

python - 使用循环从列表中查找所有唯一的单词

c# - 登录后将用户重定向回原始操作

python - 将有序字典列表转换为嵌套列表

python - 在 python 中重新组合列表/字典

python - 如何将来自不同列表的数据合并到各自的行中?