在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']]
答案 0 :(得分:2)
将它们组合为单个字符串(或者,如果这样就将它们保留为原来的样子),然后用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();
请注意,如果您的输入中包含空格(例如..., "and", "san antonio", ...
),则可能需要进行一些调整。
答案 1 :(得分:2)
为此,您可以使用System.Linq.GroupBy进行一些修改,以将键添加为给定单词之前的“ and”数。
分组方法:
static string[][] GroupByWord(string[] input, string word)
{
var i = 0;
return input.GroupBy(w =>
{
if (w == word)
{
i++;
return -1;
}
return i;
})
.Where(kv => kv.Key != -1) // remove group with "and" strings
.Select(s => s.ToArray()) // make arrays from groups ["visit", "houston"] for example
.ToArray(); // make arrays of arrays
}
调用方法:
var input = new[] { "visit", "houston", "and", "san", "antonio", "and", "austin", "and", "corpus", "christi" };
var result = GroupByWord(input, "and");
答案 2 :(得分:0)
使用循环的更简单方法。
IEnumerable<IEnumerable<string>> GetList(IEnumerable<string> source)
{
while(source.Any())
{
var returnValue = source.TakeWhile(x=>!x.Equals("and")).ToList();
yield return returnValue;
source = source.Skip(returnValue.Count()+1);
}
}
您现在可以做
var words = new[] { "visit", "houston", "and", "san", "antonio", "and", "austin", "and", "corpus", "christi" };
var result = GetList(words);
输出