Click here to Skip to main content
15,917,645 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
Hi,

I need to add class to the list if the list does not already contains the class

I am trying something like this, but I do not understand how tto proceed further

C#
numofBuses = "3";
                select1 = "Red";
                select2 = "Yellow";
                select3 = "Green";
                select4 = "";


                GWmsgDetailsList = ResponseTimeofMsgs(numofBuses, select1, select2, select3, select4);
                
                foreach (var GatewayMessageDetails in GWmsgDetailsList)
                {


                    
                    GWmessageDetailsList.Add(GatewayMessageDetails);

                }
                
                select1 = "Red";
                select2 = "Green";
                select3 = "Yellow";
                select4 = "";

                GWmsgDetailsList = ResponseTimeofMsgs(numofBuses, select1, select2, select3, select4);
                foreach (var GatewayMessageDetails in GWmsgDetailsList)
                {
                     //if(GWmessageDetailsList.MsgId.Contains
                    GWmessageDetailsList.Add(GatewayMessageDetails);

                }


The foreach loop for first time is ok
But when it comes to second time , I need to check whether it the list class already contains the same MsgId or not, then I need to procedd.

Can anyone help me in writing the code for this

Thanks in advance
Posted
Comments
BillWoodruff 12-Mar-14 22:58pm    
Like almost all your questions posted here, you leave out critical pieces of information.

In this case, you don't show us the declaration of 'GWmsgDetailsList.

Also, repeating the code that inserts the same instances of the Class into 'GWmsgDetailsList makes no sense, at all.

1 solution

Assuming you are looking to see if an item exists with the same MsgId, this should work:

C#
foreach (var GatewayMessageDetails in GWmsgDetailsList)
{
       if(!GWmessageDetailsList.Any(g=> g.MsgId == GatewayMessageDetails.MsgId)
           GWmessageDetailsList.Add(GatewayMessageDetails);

}
 
Share this answer
 

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