2
Good evening, I am creating a sales system (college work) that has a simple registration of Clients (name and Cpf), we are working with the Project in layers, I am having difficulty because I am trying to validate if the CPF already exists in the list using FOREACH, but it doesn’t seem to be working because it’s accepting all the CPF’s and at the time I ask for a re-turn of the list, it’s not returning me anything... what’s wrong with the validation of Foreach? Thank you in advance!.
Code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VendasOsorioA.Model;
namespace VendasOsorioA.DAL
{
class ClienteDAO
{
private static List<Cliente> clientes = new List<Cliente>();
public static void CadastrarCliente(Cliente c)
{
foreach (Cliente ClienteCadastrado in clientes)
{
if (c.Cpf.Equals(ClienteCadastrado.cpf))
{
Console.WriteLine("CPF JÁ EXISTE NA BASE, CADASTRO RECUSADO.");
}
else
{
clientes.Add(c);
Console.WriteLine("CLIENTE CADASTRADO COM SUCESSO.");
}
}
}
public static List<Cliente> RetornarClientes()
{
return clientes;
}
}
}
A pity not to show time, minute and second of the answers so that ignores like these do not happen. But all right, I understand your point of view.
– Victor Laio
Just keep the mouse pointer/mouse over the time pointers, which has exact details of each occurrence: https://i.stack.Imgur.com/Izxh3.png
– Bacco
Honestly, it doesn’t matter to me, it just matters if you helped the kid out there or not and somebody learned something from it. -2 rep for helping someone is a cheap price to pay yourself :)
– Victor Laio
So you notice the exchange of the word Singleordefault() for Any() and you don’t notice the difference between the comparison within the LINQ? No more...
– Victor Laio
I withdraw the accusation of copying with apology. I think it would be more constructive for Marconcilio to have given a suggestion of improvement with comment. However your answer still has information that is not correct.
porque imagina quando sua base possuir milhares de dados, qual seria a performance do foreach()
TheAny
has the same performance asforeach
with data in memory– Bruno Costa
Apology accepted, it’s exactly what I thought, why he didn’t suggest an improvement. However Any() has a particularity that when it finds the first record specified by the clause, it stops its execution and already returns the result, not going through all the data.
– Victor Laio
Victor, this is exactly the algorithm with the
foreach
if implemented correctly.– Bruno Costa
In the end it will really give everything in the same, just take care with the mode that is implemented. But an Any() is not much more beautiful to see than a foreach()? rsrs
– Victor Laio