1

Good Day Everyone. I'm creating a Xamarin.Forms Portable Application I just want to ask how am I going to convert this expression from List to ObservableCollection. Take a look at the 'ToList();' code. I don't know how to change it in order for it to read an observable collection.

 CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList();

I'm having problem how to do this because I prefer to use an ObservableCollection rather than the List. So I declare the CustomerList as ObservableCollection.

    public ObservableCollection<Customer> CustomerList
    {
        get
        {
            return _customerList;
        }
        set
        {
            _customerList = value;
            OnPropertyChanged();
        }
    }

Is there anyway to do this? Thanks a lot.

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
Jaycee Evangelista
  • 1,107
  • 6
  • 22
  • 52

2 Answers2

8

ObservableCollection <T> have constructor which takes IEnumerable <T>

Example:

ObservableCollection<Customer> myCollection = new ObservableCollection<Customer>(myList);

Raskayu
  • 735
  • 7
  • 20
  • i'm creating a searchbar, so what should be my actual code above be like? – Jaycee Evangelista Aug 10 '16 at 08:27
  • Initializing an Observable collection kills its purpose. Use `Remove()` and `Add()` – Rohit Vipin Mathews Aug 10 '16 at 08:44
  • In your coude can look like `CustomerList = new ObservableCollection( _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList() );` – Raskayu Aug 10 '16 at 08:46
  • 1
    For first time you can create as per @Raskayu, but on subsequent calls intead of calling the constructor use Remove() and Add() methods of Observable collection. Try reading through - http://stackoverflow.com/questions/4279185/what-is-the-use-of-observablecollection-in-net – Rohit Vipin Mathews Aug 10 '16 at 10:54
  • @Rohit Whenever I put your codes, my SearchBar doesn't seem to work anymore. – Jaycee Evangelista Aug 10 '16 at 11:27
3

You can use the constructor:

public ObservableCollection( 
    List<T> list 
)

https://msdn.microsoft.com/en-us/en-en/library/ms653202(v=vs.110).aspx

Just create a new ObservableCollection and pass the list as an argument to the constructor.

Oscar
  • 13,594
  • 8
  • 47
  • 75