I would like to use an Array instead of IF, I think that is more efficient but I don't how exactly do it sorry, I am new in C#, can someone just give me an good example please? I have a lot of Cliente.Contains and I think "If" is not the correct way, this is the code:
if (Cliente.Contains("0003919026"))
{
nombreCliente = "TELMOV";
}
if (Cliente.Contains("0002402248"))
{
nombreCliente = "Workplay S.A. DE C.V.";
}
if (Cliente.Contains("0009206605"))
{
nombreCliente = "SISTEMAS Y SERVICIOS DE (SYSCOM)";
}
CadenaRes = "Se proceso el archivo el dia " DateTime.Now.ToString() "\n" "El archivo con nombre: " nombreCliente;
Console.WriteLine("Carga Satisfactoria: {0} ", transfer.FileName);
CodePudding user response:
I think you can achieve your task using Dictionary like following:
var dic = new Dictionary<string, string>();
dic.Add("0003919026", "TELMOV");
dic.Add("0002402248", "Workplay S.A. DE C.V.");
dic.Add("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)");
dic.Add("0009206605", "Se proceso el archivo el dia" DateTime.Now.ToString() "\n" "El archivo con nombre: " nombreCliente);
nombreCliente = dic.FirstOrDefault(x => Cliente.contains(x));
You can also use list of a class containing your key and value. Then use linq to get your required value.
CodePudding user response:
Technically, you can organize substitution pairs (what to find and what to show) into a collection, say an array and implement something like this:
using System.Linq;
...
string nombreCliente = ...
(string find, string show)[] subs = new[] {
("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)"),
("0002402248", "Workplay S.A. DE C.V."),
//TODO: Add more pairs here
};
// Reverse: according to the code in the question, the later pair should prevail;
// if it's not possible we can drop .Reverse()
foreach (var pair in subs.Reverse())
if (Cliente.Contains(pair.find)) {
nombreCliente = pair.show;
break;
}
CadenaRes = string.Join(Environment.NewLine,
$"Se proceso el archivo el dia {DateTime.Now}",
$"El archivo con nombre: {nombreCliente}",
);
Console.WriteLine($"Carga Satisfactoria: {transfer.FileName}");
But I doubt in underlying logic: we are looking for just a fragment, and the assign nombreCliente
;
what if Cliente
is combined, say 0009206605 and (0002402248)
?