1

I have ObservableCollection list and i want to sort it to alphabet for ex : when i enter 3 names (basketball , arab , club) the output : basketball, arab, club

and i want it like : arab, basketball, club,

this code for ObservableCollection :

        public ObservableCollection<Contact> ContactList { get; set; }

and this code of Add and Delete items

 public ContactsListView()
        {

            InitializeComponent();
            ContactList = new ObservableCollection<Contact>();

            BindingContext =  new Contact();
            MessagingCenter.Subscribe<Contact>(this, "addNew", (addItem) =>
            {
                ContactList.Add(new Contact { Name = addItem.Name, PhoneNo = addItem.PhoneNo, Address = addItem.Address, NickName = addItem.NickName });

            });

            MessagingCenter.Subscribe<Contact>(this, "deleteContact", (Account) =>
            {
                ContactList.Remove(Account);
            });

                        MyListView.ItemsSource = ContactList;
            AddNewContact.Clicked+= AddNewContact_Clicked;
        }

Robote
  • 17
  • 1
  • 9
  • Possible duplicate of [Sort ObservableCollection through C#](https://stackoverflow.com/questions/19112922/sort-observablecollectionstring-through-c-sharp) – Mohammad Roshani May 05 '19 at 09:17

3 Answers3

0

You can use linq to sort like this:

var sortedContactList = ContactList.ToList().OrderBy(x => x.Name);

You will need to add using System.Linq; at the top of your file.

iakobski
  • 1,000
  • 7
  • 8
0

The ObservableCollection class itself does not have a sort method. but by using collection you can recreate it.

var ContactList = new ObservableCollection<string> { "club", "arab", "basketball", };
 ContactList = new ObservableCollection<string>(ContactList.OrderBy(i => i));
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
0

Rather than recreating a new sorted ObservableCollection to the ContactList, you could use Move method to sort the current ContactList.

private void SortContacts()
{
    // order by name
    var sortedContact = ContactList.OrderBy(x => x.Name).ToList();

    for (var i = 0; i < sortedContact.Count; i++)
        ContactList.Move(ContactList.IndexOf(sortedContact[i]), i);
}

Call above method after adding or deleting contact item.

Luthfi
  • 478
  • 1
  • 3
  • 16