Hello, I'm just starting to dive into the world of development, I wanted to ask for advice on how to improve the following code:

JobKind jobKind = 0; foreach (JobKind value in Enum.GetValues(typeof(JobKind))) { var enumIntValue = (int)value; if (model.JobKinds.Contains(enumIntValue.ToString())) { var checkedSymbol = char.Parse(enumIntValue.ToString()); if ((model.JobKinds.LastIndexOf(checkedSymbol) - model.JobKinds.IndexOf(checkedSymbol)) == 0) jobKind = jobKind | value; } } 

JobKind is an enumeration with the [Flags] attribute. At the entrance is a model that contains a string field - types of specialties. There is a listing. For convenience, you can specify the numbers of sets of specialties (for example, 2,4,5 ). The numbers are equal to the value of the fields in the listing. This code forms a bit field and enumerations from a string. I didn’t find how to convert a string like 2,4,5 into a listing in a more elegant way, so I would like to ask your advice on how to improve the readability of the code, etc.

  • What type of model.JobKinds ? and an example of the value of this field - Grundy
  • This is a string, numbers are entered there, for example, 2,4,8 - the numbers of fields of the JobKinds enumeration. - QuaternioNoir
  • oh ooh ooh, what do you think if you have one number 32 in the line, what will return Contains when you pass the value 2 ? - Grundy
  • Yeah, here I just flew. - QuaternioNoir

1 answer 1

In this case, it is better not to go through all the enumeration values, but to organize the convolution of the string.

To do this, split it by the separator , using the Split function, and then minimize it, for example, using the Aggregate method

 var jobKind = model.JobKinds.Split(',') .Aggregate((J)0, (acc, cur) => { var value = (J)int.Parse(cur); // приводим элемент из строки в число, и затем в значение enum return acc | value; // объединяем значения и возвращаем }); 

A bit more compact, Aggregate calls might look like this:

 .Aggregate((J)0, (acc, cur) => acc | (J)int.Parse(cur)) 
  • Indeed, thanks - QuaternioNoir
  • @PlayGroundLegend Select this answer as accepted if it suits you. - Vadim Ovchinnikov