使用linq按字符串出现分组
本文关键字:字符串 linq 使用 | 更新日期: 2023-09-27 18:24:18
谷歌搜索没有任何帮助,所以我在这里问:如何根据某个字符串的出现对字符串进行分组?
宠物动物园的示例数据
Name: My little petting zoo CRLF
Owner: Atrotygma CRLF
AverageVisitors: 100 CRLF
PricePerTicket: 5 CRLF
ZooSize: 20 CRLF
Animal: Goat CRLF
Age: 5 CRLF
FavoriteFood: Grass CRLF
Animal: Sheep CRLF
Age: 3 CRLF
Legs: 2 ( + 2 wheels) CRLF
Animal: Dire Wolf CRLF
Name: Puppy CRLF
Size: 20 CRLF
Age: 10.000 CRLF
Classification: Still alive CRLF
目标:动物应该被分组在一起(指标:动物),每只动物后面都有其(随机、不可预测的)属性(直到下一只动物)。
Name: My little petting zoo
Owner: Atrotygma
AverageVisitors: 100
PricePerTicket: 5
ZooSize: 20
Animal: Key: Goat
Age: 5
FavoriteFood: Grass
Animal: Key: Sheep
Age: 3
Legs: 2 ( + 2 wheels)
Animal: Key: Dire Wolf
Name: Puppy
Size: 20
Age: 10.000
Classification: Still alive
我知道这是一种可怕的数据形式,但它不是我的,我无法更改任何内容。
考虑在"Animal:"上使用Split
来分解字符串。然后,您可以对生成的一组动物字符串执行您喜欢的操作。
这将使您以所需的格式显示字符串。首先,我列出了你的字符串(带有适当的拆分选项),获取"动物"单词出现的索引,然后(这是我的想法,也许是很久以前的事了,哈哈),用一个字符串之间的字符串制作一个临时列表,并在原始列表中循环修改那些特定的字符串:
List<string> words = str.Split(new char[]{''r',''n'},
StringSplitOptions.RemoveEmptyEntries).ToList();
int[] indexes = words.Select((b, i) => b.StartsWith("Animal") ? i : -1).Where(i => i != -1).ToArray();
List<string> temp = new List<string>();
for (int i = 0; i < indexes.Length; i++)
{
if (i == indexes.Length - 1)
temp.AddRange(words.GetRange(indexes[i] + 1, words.Count - (indexes[i] + 1)));
else
temp.AddRange(words.GetRange(indexes[i] + 1, indexes[i + 1] - (indexes[i] + 1)));
}
for (int y = 0; y < words.Count; y++)
{
if (temp.Contains(words[y]))
words[y] = "'t" + words[y];
}
经过这段漫长的旅程,你的单词列表将具有所需的格式。
编辑:捷径:
List<string> words = str.Split(new char[]{''r',''n'},
StringSplitOptions.RemoveEmptyEntries).ToList();
int[] indexes = words.Select((b, i) => b.StartsWith("Animal") ? i : -1).Where(i => i != -1).ToArray();
for (int i = 0; i < indexes.Length; i++)
{
if (i == indexes.Length - 1)
words = words.Select(s => words.GetRange(indexes[i] + 1, words.Count - (indexes[i] + 1)).Contains(s) ? s = "'t" + s : s).ToList();
else
words = words.Select(s => words.GetRange(indexes[i] + 1, indexes[i + 1] - (indexes[i] + 1)).Contains(s) ? s = "'t" + s : s).ToList();
}
还有一些优化。。。。。。