我要解决的问题如下:
我有一个List<string>
,我们称它为“ initialList
”。
我需要与该列表中的所有字符串进行交互,因此我必须对其进行枚举。但是,问题来了,每次我互动时,我都必须取“ x”个元素。x
是new Random().Next(_minValue, _maxValue);
,因此每次都是随机的。
这是我想做的一个真实的例子:
假设列表initialList
包含以下元素:test, test2, test3, test4, test5, test6, test7, test8, test9, test10, test11, test12
。
我想遍历所有元素,一次取2-3个字符串,然后用组合的字符串保存一个新字符串。
因此,一种可能的输出(取决于随机返回的值会有所不同)是:
{ "test", "test1", "test2" },
{ "test3", "test4" },
{ "test5", "test6" },
{ "test7", "test8" },
{ "test9", "test10", "test11" },
{ "test12" }
我的想法是:
for (var i = 0; i < _users.Count; i += _random.Next(_minMentions, _maxMentions + 1))
{
var mergedString = ?? // get the values of the next _random.Next(_minMentions, _maxMentions + 1) strings
}
我当时在想,但是如果我在循环外生成随机数,那么它将始终是相同的。我希望每次的字符串数量都是随机的。
另外,想到通过选择带有索引的元素来进行LINQ,但不知道如何从那里继续。
任何帮助表示赞赏,谢谢。
最佳答案
我认为最好的解决方案是使用LINQ Skip
跳过您已经处理的元素,并使用Take
提取随机数量的元素。
const int _minValue = 2;
const int _maxValue = 4; // note max of random is exclusive, so this config takes 2 or 3 elements
var _random = new Random(Guid.NewGuid().GetHashCode());
List<string> initialList = new List<string>{"test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12"};
var currentPosition = 0;
while (currentPosition < initialList.Count()) {
var toTake = _random.Next(_minValue, _maxValue);
var mergedString = string.Join(", ", initialList.Skip(currentPosition).Take(toTake));
currentPosition += toTake;
}
请注意,此代码可能导致最后一个
mergedString
仅包含一个元素(最后一个)。工作示例:C# Fiddle。
关于c# - 如何将字符串列表拆分为较小的字符串列表 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825134/