基于下一个元素的值的LINQ条件聚合 [英] LINQ conditional aggregation based on next elements' values

查看:66
本文介绍了基于下一个元素的值的LINQ条件聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此伪代码的LINQ等效项是什么:给出了一个字符串列表,对于不包含制表符的每个字符串,将其(使用竖线分隔符)连接到前一个字符串的末尾,并返回结果序列"?

What's a good LINQ equivalent of this pesudo-code: "given a list of strings, for each string that doesn't contain a tab character, concatenate it (with a pipe delimiter) to the end of the previous string, and return the resulting sequence" ?

更多信息:

我有一个List<string>代表制表符分隔的文本文件中的行.每行的最后一个字段始终是多行文本字段,并且该文件是由错误处理的带有错误的系统生成的,该错误处理系统使用嵌入式换行符来处理字段.所以我最终得到一个这样的列表:

I have a List<string> representing lines in a tab-delimited text file. The last field in each line is always a multiline text field, and the file was generated by a buggy system that mishandles fields with embedded newlines. So I end up with a list like this:

1235 \t This is Record 1
7897 \t This is Record 2
8977 \t This is Record 3
continued on the next line
and still continued more
8375 \t This is Record 4

我想通过将所有孤立行(没有制表符的行)连接到上一行的末尾来合并此列表.像这样:

I'd like to coalesce this list by concatenating all the orphan lines (lines with no tab characters) to the end of the previous line. Like this:

1235 \t This is Record 1
7897 \t This is Record 2
8977 \t This is Record 3|continued on the next line|and still continued more
8375 \t This is Record 4

for()循环解决这个问题很容易,但是我试图提高LINQ技能,我想知道是否有一个合理有效的LINQ解决方案来解决这个问题.有吗?

Solving this with a for() loop would be easy, but I'm trying to improve my LINQ skills and I was wondering if there is a reasonably efficient LINQ solution to this problem. Is there?

推荐答案

这不是LINQ应该解决的问题. LINQ专为枚举而设计,而这最好通过迭代来解决.

This is not a problem that should be solved with LINQ. LINQ is designed for enumeration, whereas this is best solved by iteration.

正确枚举序列意味着没有一个项目对其他项目有所了解,这显然不适用于您的情况.使用for循环,以便您可以整洁地按顺序依次遍历字符串.

Enumerating a sequence properly means no item has knowledge of the other items, which obviously won't work in your case. Use a for loop so you can cleanly go through the strings one by one and in order.

这篇关于基于下一个元素的值的LINQ条件聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆