如何使用 linq 按顺序计算每组中的项目数?
例如,我有一个整数序列,
1122211121
我想要一些字典/匿名类显示:
item | count
1 | 2
2 | 3
1 | 3
2 | 1
1 | 1
For example, I have a sequence of integers
1122211121
I'd like to get some dictionary/anonymous class showing:
item | count
1 | 2
2 | 3
1 | 3
2 | 1
1 | 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想更加 Linqy,可以在
let
子句中完成previous
和idx
的初始化。函数式编程很好,但恕我直言,在这种情况下,在 C# 中我肯定会选择过程式方法。
initialization of
previous
andidx
could be done inlet
clause if you want to be even more Linqy.Functional programming is nice, but imho this is a case where in C# I would surely choose rather procedural approach.
您希望执行类似于 morelinq 项目中的“Batch”运算符的操作,然后输出组的计数。
不幸的是,morelinq 中的批处理运算符只接受一个大小并返回按该大小批处理的存储桶(或者在我查看 morelinq 时确实如此)。为了纠正这个缺陷,我必须编写自己的批处理实现。
这是我公开了验证输入参数的各种公共重载的私有版本。您希望您的breakCondition具有以下形式:
对于您的示例序列,这应该为您提供:
{1, 1}, {2, 2, 2}, {1, 1, 1}, {2} , {1}
从这里开始,抓取每个序列的第一项然后对序列进行计数就很简单了。
编辑:为了协助实施-
您的代码将是:
除了我在自己的代码库中使用的私有方法及其重载之外,我还没有编译和测试任何这些,但这应该可以解决您的问题以及您遇到的任何类似问题。
You're looking to do something like the "Batch" operator in the morelinq project, then output the count of the groups.
Unfortunately, the batch operator from morelinq just takes a size and returns buckets batched by that size (or it did when I was looking at morelinq). To correct this deficiency, I had to write my own batch implementation.
This is the private version that I expose various public overloads which validate input parameters. You would want your breakCondition to be something of the form:
This should give you, for your example sequence:
{1, 1}, {2, 2, 2}, {1, 1, 1}, {2}, {1}
From here, grabbing the first item of each sequence and then counting the sequence are trivial.
Edit: To assist in implementation -
Your code would then be:
I haven't compiled and tested any of this except the private method and its overloads that I use in my own codebase, but this should solve your problem and any similar problems you have.
嗯...稍微短一点(注意处理偶数/奇数出现计数的双重分离调用):
Wel... a bit shorter (notice the double Separate call to deal with even/odd occurrences counts) :