Home > other >  How update Collection in infinity Loop
How update Collection in infinity Loop

Time:07-29

I'm trying to add only items that are new to the ObservableCollection, so as not to create duplicates. Everything is in an infinite loop so I can add the new ones. The problem is that I can't figure out the best way to prevent duplicates in the list. To prevent the program from throwing me an exception for comparing items in an empty sheet. So I add them first and if they don't meet the condition, I remove them. But then it flashes on the screen, e.g. in a table, as new items are added. So what to do? Thanks for any suggestions

 bool help = true;
           
            do
            {

                using (var client = new ImapClient())
                {
                    using (var cancel = new CancellationTokenSource())
                    {

                   
                        client.Connect(emailParser.ServerName, emailParser.Port, emailParser.isSSLuse,
                            cancel.Token);
                       
                        //client.AuthenticationMechanisms.Remove("XOAUTH");

                        client.Authenticate(emailParser.Username, emailParser.Password, cancel.Token);

                       
                        var inbox = client.Inbox;
                        inbox.Open(FolderAccess.ReadOnly, cancel.Token);

                        Console.WriteLine("Total messages: {0}", inbox.Count);
                        Console.WriteLine("Recent messages: {0}", inbox.Unread);
                        

                      
                        for (int i = 0; i < inbox.Count; i  )
                        {
                            var message = inbox.GetMessage(i, cancel.Token);

                                alerts.Add(message); // I Think the problem is here

                            for (int j = 0; j < alerts.Count-1; j  )
                            {
                                if (alerts[j].MessageId.Equals(message.MessageId))
                                {
                                    alerts.Remove(message);
                                }
                            }
                        
                        }
                        Console.WriteLine(alerts.Count);
                        alerts.Count();
                    
                    }
                    client.Disconnect(true);
                    
                }
          
        } while (help != false);

CodePudding user response:

Use LINQ's Any method for enumerables which is safe against empty collections

CodePudding user response:

How about you not add the item unless the condition is met, instead of adding and removing later? If you do, your for loop becomes

for (int i = 0; i < inbox.Count; i  )
{
    var message = inbox.GetMessage(i, cancel.Token);
    if (!alerts.Any(x => x.MessageId.Equals(message.MessageId))
    {
        alerts.Add(message);
    }
}
  • Related