Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public  class Logger
{
   string module { get; set; }
   private  string sMessage { get; set; }
   public static string sNewMessage = string.Empty;
   public static List<Logger> logMessages = new List<Logger>();
   private static string sLogMessage;


C#
private static void Log(string message, string type, string module)
{
 //here every message i entered is addedin a list now i want to check if message already exists ???do not add 
bool bMessageexists = logMessages.Contains(new Logger() { sMessage });

but even i entered existing message it returns false my code is not working correctly

What I have tried:

i have crated a list of string meggages which is ok for example HELLO message but i want to check if it already exists i mean if list already contains HELLO message then do not add in a list i have written a code above but its not working correctly even i entered same message 10 times bool returns false??
Posted
Updated 16-Nov-16 21:19pm
v3
Comments
Ralf Meier 17-Nov-16 2:59am    
Perhaps you should show the code behind each of your methods ...

1 solution

If your logger class exposes its current message, then you need to compare that:
C#
bool bMessageexists = logMessages.Contains(logger=>logger.Message == sMessage);

If not, you will need to override Logger.Equals, to compare the messages in both objects.
C#
class Logger {
    string sMessage;
    //...
    public override bool Equals(object obj) {
        if (obj is Logger)
            return sMessage == ((Logger)obj).sMessage;
        return false;
    }
}
 
Share this answer
 
v2
Comments
Afzaal Ahmad Zeeshan 17-Nov-16 3:19am    
5ed.
Member 11000455 17-Nov-16 4:19am    
logMessages.Add(new Logger() { sMessage = message });//here every time i add a message it is added to a list corretly

and i have done
bool bMessageexists = logMessages.Contains(new Logger() { sMessage = message}); //but it returns false.
tried ur code LINQ expression its not working
Midi_Mick 17-Nov-16 4:37am    
Ok, now that you have included your Logger class definition, it's easier to answer.
Because you have declared sMessage as private, you will have to implement the Equals override in the Logger class (as per my answer above), as the Linq query does not have access to the field.
Note: If you override Equals, you also must override GetHashCode. In this case, I would simply return sMessage.GetHashCode() from that override.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900