首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从c#中的主列表创建多个唯一条目列表

从c#中的主列表创建多个唯一条目列表
EN

Stack Overflow用户
提问于 2015-09-08 19:50:07
回答 3查看 194关注 0票数 2

我需要处理出站SMS队列并创建批量消息。排队列表可能包含发往同一人的多条消息。批处理不允许这样做,因此我需要遍历主出站队列,并根据需要创建尽可能多的批处理,以确保它们包含唯一条目。示例:

代码语言:javascript
运行
复制
Outbound queue = (1,2,3,3,4,5,6,7,7,7,8,8,8,8,9)

结果是...

代码语言:javascript
运行
复制
 batch 1 = (1,2,3,4,5,6,7,8,9)
    batch 2 = (3,7,8)
    batch 3 = (7,8)
batch 4 = (8)

我可以很容易地检查重复项,但我正在寻找一种灵活的方法来生成额外的批次。

谢谢!

EN

回答 3

Stack Overflow用户

发布于 2015-09-08 20:10:35

看看使用Enumerable.ToLookup和其他LINQ方法的这种方法:

代码语言:javascript
运行
复制
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>的列表

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2015-09-08 20:03:18

根据所使用的特定数据结构,可以使用Linq GroupBy扩展方法(假设队列为某些类型的T实现IEnumerable<T> )由同一用户进行分组;然后,可以分别迭代组。

票数 0
EN

Stack Overflow用户

发布于 2015-09-08 20:27:26

一种天真的方法是遍历输入,边走边创建并填充批:

代码语言:javascript
运行
复制
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;
}

输出:

代码语言:javascript
运行
复制
1, 2, 3, 4, 5, 6, 7, 8, 9
3, 7, 8
8
8

我相信这可以用函数式的方式来缩短或编写。我尝试过使用GroupBy、Distinct和Except,但是不能那么快地理解它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32457068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档