计算列表中的项目< string> [英] Count items in list<string>
问题描述
大家好,我在通用列表中有一组字符串因此
Hi all, I have a collection of strings in a generic list thus
H,1000,28-09-2017
L,30,Pete
L,50,Pete
H,200,29-09-2017
L,35,Pete
L,45,Pete
L,55,Pete
etc....
我如何(如果可能的话,使用Linq)计算每个L之间的行数 H行,因为我迭代列表?基本上,H表示包含n个细节线的组的开始,例如,对于第一组,我想形成一个字符串,如
How can I ( using Linq if possible ) count the number of "L" lines between each "H" line as I iterate over the list ? Basically the "H" indicates the start of a group containing n detail lines, e.g. for the first group I would like to form a string like
H,1000,28-09-2017,80,Pete,2 - where 2 = the number of L lines and 80 the sum of the amounts
我尝试过:
我当前正在进行一次循环求和并计算当我去
What I have tried:
I currenly do it in a while loop summing and counting as I go
推荐答案
我强烈怀疑常规循环将是你最好的选择。但如果你真的想强迫它:
I strongly suspect a regular loop will be your best option. But if you really want to force it:
IEnumerable<string> headerLinesWithCounts = source
.Select((value, index) => (value: value, index: index))
.Where(pair => pair.value[0] == 'H')
.Select(pair => (value: pair.value, lines: source.Skip(pair.index + 1).TakeWhile(v => v[0] != 'H')))
.Select(pair =>
{pair.value},{pair.lines.Count()});
输出:
H,1000,28-09-2017,2
H,200,29-09-2017,3
或者,如果您还需要在输出中包含这些行:
Or, if you need to include the lines in the output as well:
IEnumerable<string> headerLinesWithCounts = source
.Select((value, index) => (value: value, index: index))
.Where(pair => pair.value[0] == 'H')
.Select(pair => (value: pair.value, lines: source.Skip(pair.index + 1).TakeWhile(v => v[0] != 'H')))
.Select(pair => (header:
{pair.value},{pair.lines.Count()},行:pair.lines))
.SelectMany(pair = > Enumerable.Repeat(pair.header, 1 )。Concat(pair.lines));
"{pair.value},{pair.lines.Count()}", lines: pair.lines)) .SelectMany(pair => Enumerable.Repeat(pair.header, 1).Concat(pair.lines));
输出:
H,1000,28-09-2017,2
L,30,Pete
L,50,Pete
H,200,29-09-2017,3
L,35,Pete
L,45,Pete
L,55,Pete
注意:这是使用新的 ValueTuple [ ^ ]类型。如果你的编译器不支持它,你可以使用匿名类型。
NB: This is using the new ValueTuple[^] type. If your compiler doesn't support it, you can use anonymous types instead.
这篇关于计算列表中的项目< string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!