There is a program that generates code by two selected parameters (color and capital). The parameters themselves are stored in a text file, in the form of color format lines : small capital: link .

Example:

102:classic:capitels/0206102.png 103:nonstandard1:capitels/0301103.png 104:seriya:capitels/0405104.png 

Some capitals are missing in certain colors. In this case, it is necessary for the program to print a specific string.

Program:

 List<string> data = new List<string>(); string[] chosen_colors; string[] chosen_caps; public Form1() { InitializeComponent(); var splitChars = new[] { ':' }; try { data = File.ReadLines("config.txt").ToList(); } catch (Exception e) { MessageBox.Show("Файл конфигурации не найден:\n" + e.Message); } } private void generate_Click(object sender, EventArgs e) { chosen_colors = colorsList.CheckedItems.OfType<string>().ToArray(); chosen_caps = capList.CheckedItems.OfType<string>().ToArray(); foreach (string cap in chosen_caps) { code.Text += "'" + cap + "': {\n"; foreach (string s in data) { string[] array = s.Split(new char[] { ':' }, 3); if (array[1] == cap) { foreach (string chosenColor in chosen_colors) { if (array[0] == chosenColor) code.Text += "\t'" + array[0] + "':'" + array[2] + "',\n"; } } } code.Text += "},\n"; } } 

Those. Now, if the selected capitals are not in color 102, then the program will not output anything. I also need to display a string of the form '102': '/no-capitel.png' , how to write a check for the absence of a selected capital in a certain color?

I hope explained clearly

  • Go through all the lines from 102 at the beginning, check for the presence of the necessary small caps, if not found - output. What is the problem? - Vladimir Martyanov
  • I don’t quite understand how exactly this can be realized in the body of the cycle - Danny
  • That's exactly what you can do. What are <b> specific </ b> problems with? - Vladimir Martyanov
  • Create a variable with the results before the cycle. Go through the loop and search for the necessary data, taking the found into the variable. After the loop, check the variable with the results if there was anything and perform the necessary actions. Is done. And for good it would be necessary to implement a separate class that will search and return the result. - Alex Krass
  • 3
    I do not recommend using the colon as a delimiter, since it can be included in the drive name c: \ although it is not allowed in file names. It is better to use the vertical line | - Cerbo

2 answers 2

try something like this:

 var data = File.ReadLines(path) .Select(s => s.Split(new[] { ':' }, 3)) .Select(triple => new { ColorIdx = int.Parse(triple[0]), Capital = triple[1], Reference = triple[2] }); var colors = new HashSet<int>(data.Select(o => o.ColorIdx)); var dict = data.GroupBy(o => o.Capital) .ToDictionary(g => g.Key, g => g.ToDictionary(o => o.ColorIdx, o => o.Reference)); foreach (var entry in dict) { Console.WriteLine("Capital: " + entry.Key); var colorMapping = entry.Value; foreach (var color in colors) { string reference; if (colorMapping.TryGetValue(color, out reference)) Console.WriteLine("\tColor: {0}, reference: {1}", color, reference); else Console.WriteLine("\tColor: {0}, reference: default", color); } } 
     string result=""; //Формируем лист цветов, которые еще не встречались в обработке (изначально он повторяет список выбранных цветов) List<string>ColorsStillNotUsed=chosen_colors.Tolist(); foreach (string record in data) //Перебираем записи из файла { //не используй разделитель ":", потому что в записях используется путь, могущий содержать такой символ. string[] parts = record.Split(new char[] { '|' }); if(parts.Length==3) //Синтаксис строки в файле правильный { if(chosen_colors.Contains(parts[0])&&chosen_caps.Contains(parts[1]))//Если цвет и капитель соответствуют выбранным { ColorsStillNotUsed.RemoveAll(x=>x==parts[0]); //Убираем цвет из списка неиспользованных result+=string.Format("\t'{0}:{1}',\n", parts[0],parts[2]);//Добавляем в запись } } } foreach (string unused in ColorsStillNotUsed) //Перебирая цвета, выбранные но не встреченные, генерируем соответствующие строки { result+=string.Format("\t'{0}:{1}',\n", unused,"/no-capitel.png"); } 

    Unused colors will always be at the end of the list. If the order is important, you can place the result not into a string but into an array or IEnumerable and then sort the Alphanumeric strings by the first characters (color number).

    • Error in if (chosen_colors.Contains(parts[0]) && chosen_caps.Contains(parts[1])) The value cannot be undefined. Parameter name: source - Danny
    • I wrote right here, without checking the syntax. Try replacing if (parts == 3) with if (parts.Length == 3) maybe this is the reason. In general, any code on this resource is intended only to show the direction in which you need to move, as a rule, even elementary checks for possible errors are missing, because it means that the person who asked the question creatively processes it independently for his specific needs. - Anatoly Nikolaev