c# 获取在列表中的某个元素之间分组的新元素列表

标签 c# linq

在 C# 中,如何获取通过落在某个元素之间分组的新元素列表。例如,如果我的列表是 ['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']

我想将“and”之间的城市提取到一个在“and”之间分组的新列表中,这样两个单词名称城市就在一个组中

在 python 中,您可以使用 itertools,但如何在 c# 中实现此目的?

import itertools as itt
    List =['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']
    >>> [list(g) for k, g in itt.groupby(L, key=lambda word: word=='and') if not k]

结果-

[['visit', 'houston'], ['san', 'antonio'], ['austin'], ['corpus', 'christi']]

最佳答案

将它们组合成一个字符串(或者如果它们是这样开始的,则保持原样),然后用 and 分割它,并再次分割每个子字符串:

var words = new[] { "visit", "houston", "and", "san", "antonio", "and", "austin", "and", "corpus", "christi" };

var sentence = string.Join(' ', words);  // "visit houston and san .... christi"

var cities = sentence.Split("and", StringSplitOptions.None)
                     .Select(x => x.Split(' ', StringSplitOptions.RemoveEmptyEntries))
                     .ToArray();

enter image description here

请注意,如果您的输入中包含空格(例如 ...、“and”、“san antonio”、...),则可能需要进行一些调整。

关于c# 获取在列表中的某个元素之间分组的新元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260298/

相关文章:

c# - 如何在字典键上执行 "like"?

c# - Linq 和 localhost,实体命名空间与程序命名空间不同,但仍然出现错误

c# - Winforms TableLayoutPanel 以编程方式添加行

c# - 使用 Linq 查询服务引用

c# - TextBox 和 .AppendText() 中的行的奇怪行为 - C#

c# - 如果查询字符串中的一个字段为空且为字符串格式,则返回表中的所有值

c# - 使用LINQ C#在字符串列表中查找字符出现频率最高的字符串

c# - 隐藏或删除微调器 Xamarin.Android

c# - Restsharp - 尝试序列化根节点上的 xmlns 属性时出错

c# - XSL + XML -> 用于 C# 的 PDF