Dipak
Dipak

Reputation: 1259

Avoid adding same item in Observable Collection using C#

I have following things:

ObservableCollection<dateListModel> model = new ObservableCollection<dateListModel>();

public class dateListModel
{
    public string dateSelected { get; set; }
    public string requestFor { get; set; }
    public int id { get; set; }
    public string weekDay { get; set; }
}

Adding item to ObservableCollection using following code:

public void onAddClicked(object sender, EventArgs e)
        {           
            try
            {   
                if (model.Any (p =>string.Format("{0:yyyy-MM-dd}", p.dateSelected.ToString())==string.Format ("{0:yyyy-MM-dd}",myDatePicker.Date.ToString()) == false))
                {
                    model.Add (new dateListModel {
                        dateSelected = string.Format("{0:yyyy-MM-dd}", myDatePicker.Date),
                        requestFor = requestFor.Items [requestFor.SelectedIndex],
                        id = 1,
                        weekDay = myDatePicker.Date.DayOfWeek.ToString ()
                    });

                    listview_MenuItem.ItemsSource = model;
                } 
                else
                    DisplayAlert ("Alert", "Already Exist!", "OK"); 
            }
            catch(Exception ex) 
            {
                DisplayAlert ("Alert",ex.ToString(),"OK");
            }
        }

But when I click on Add button it show "Already Exist" message even model is empty. Any how I added item in model and trying to add same item again, it allows to add in ObservableCollection. I don't want to add same date again in my Model. Where I am wrong?

Upvotes: 1

Views: 1188

Answers (2)

Keyur PATEL
Keyur PATEL

Reputation: 2329

Try this:

if (!model.Any(p => p.dateSelected.Date == myDatePicker.Date))
{
    model.Add (new dateListModel { dateSelected = string.Format("{0:yyyy-MM-dd}", myDatePicker.Date), requestFor = requestFor.Items [requestFor.SelectedIndex], id = 1, weekDay = myDatePicker.Date.DayOfWeek.ToString()});
    listview_MenuItem.ItemsSource = model;
}

You don't have to convert all the dates to the same string format initially to check if a record with that date exists in the database. Also, !Any... is equivalent to Any... == false

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29026

You can compare two dates directly without converting it to string. an additional note you need not to use .ToString() to get date in specific format, when you use so the Date is converted to a string and then the format will not be applied as you expected. If you go with .ToString() then specify format as an argument to the method(like this DateTime.Now.ToString("yyyy-MM-dd")).

In short you have to change the condition like this to make it work.

if (!model.Any(p =>p.dateSelected==myDatePicker.Date))
{

   // Add new object to the collection
}
else
   DisplayAlert ("Alert", "Already Exist!", "OK");

Upvotes: 0

Related Questions