Объединение одинаковых строк и их значений из text файла
Есть такой текст: red 1 orange 3 orange 1 blue 4 white 2 red 4 Нужно чтобы после всех манипуляций получилось red 5 orange 4 blue 4 white 2 Через Split пробовал разделять "слова" и "значения" и сравнивать между собой, но не получилось. Есть код на поиск максимального и значений и текстового файла. И вот призадумался как объединить повторяющиеся слова и просуммировать значения Сам код на поиск макс элемента:
static void Main(string[] args)
{
string[] openText = File.ReadAllLines("original.txt");
int max = 0;
string line;
for (int i = 0; i < openText.Length; i++)
{
line = openText[i];
if (GetCount(openText[max]) < GetCount(openText[i]))
{
max = i;
}
}
Console.WriteLine(GetWord(openText[max]));
}
static string GetWord(string line)
{
string[] splited = line.Split(' ');
string word = splited[0];
int count = Convert.ToInt32(splited[1]);
return word;
}
static int GetCount(string line)
{
string[] splited= line.Split(' ');
string word = splited[0];
int count = Convert.ToInt32(splited[1]);
return count;
}
Ответы (1 шт):
Автор решения: Yotic
→ Ссылка
Ответ от EvgeniyZ:
var result = string.Join(' ', text.Split().Select((x, i) => (Index: i, Item: x)).GroupBy(x => x.Index / 2).Select(x=>x.Select(v => v.Item)).GroupBy(x => x.First()).Select(x => $"{x.Key} {x.Sum(s => int.Parse(s.Last()))}"));
Мой развёрнутый ответ:
string[] input = "red 1 orange 3 orange 1 blue 4 white 2 red 4".Split(' ');
List<(string, int)> rawResult = new List<(string, int)>();
for (int i = 0; i < input.Length; i += 1)
rawResult.Add((input[i], int.Parse(input[++i])));
string result = string.Join(" ", rawResult.Select(z => (z.Item1, rawResult.FindAll(x => x.Item1 == z.Item1).Select(x => x.Item2).Sum())).Distinct().Select(z => string.Join(" ", z.Item1, z.Item2.ToString())));
Тут старый код: https://pastebin.com/hvHcx4hN