我需要处理出站SMS队列并创建批量消息。排队列表可能包含发往同一人的多条消息。批处理不允许这样做,因此我需要遍历主出站队列,并根据需要创建尽可能多的批处理,以确保它们包含唯一条目。示例:
Outbound queue = (1,2,3,3,4,5,6,7,7,7,8,8,8,8,9)
结果是...
batch 1 = (1,2,3,4,5,6,7,8,9)
batch 2 = (3,7,8)
batch 3 = (7,8)
batch 4 = (8)
我可以很容易地检查重复项,但我正在寻找一种灵活的方法来生成额外的批次。
谢谢!
发布于 2015-09-08 20:10:35
看看使用Enumerable.ToLookup
和其他LINQ方法的这种方法:
var queues = new int[] { 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9 };
var lookup = queues.ToLookup(i => i);
int maxCount = lookup.Max(g => g.Count());
List<List<int>> allbatches = Enumerable.Range(1, maxCount)
.Select(count => lookup.Where(x => x.Count() >= count).Select(x => x.Key).ToList())
.ToList();
结果是一个包含另外四个List<int>
的列表
foreach (List<int> list in allbatches)
Console.WriteLine(string.Join(",", list));
1, 2, 3, 4, 5, 6, 7, 8, 9
3, 7, 8
8
8
发布于 2015-09-08 20:03:18
根据所使用的特定数据结构,可以使用Linq GroupBy扩展方法(假设队列为某些类型的T
实现IEnumerable<T>
)由同一用户进行分组;然后,可以分别迭代组。
发布于 2015-09-08 20:27:26
一种天真的方法是遍历输入,边走边创建并填充批:
private static List<List<int>> CreateUniqueBatches(List<int> source)
{
var batches = new List<List<int>>();
int currentBatch = 0;
foreach (var i in source)
{
// Find the index for the batch that can contain the number `i`
while (currentBatch < batches.Count && batches[currentBatch].Contains(i))
{
currentBatch++;
}
if (currentBatch == batches.Count)
{
batches.Add(new List<int>());
}
batches[currentBatch].Add(i);
currentBatch = 0;
}
return batches;
}
输出:
1, 2, 3, 4, 5, 6, 7, 8, 9
3, 7, 8
8
8
我相信这可以用函数式的方式来缩短或编写。我尝试过使用GroupBy、Distinct和Except,但是不能那么快地理解它。
https://stackoverflow.com/questions/32457068
复制相似问题