Code compiles properly but while running gives error

  private ObservableCollection<Contact> GetContacts(String SearchText = null)
        {
            _contacts = new ObservableCollection<Contact>
            {
                new Contact{Name = "mosh",Status ="hi",ImageUrl= "http://lorempixel.com/100/100/people/1"  },
                 new Contact{Name = "josh",Status ="halo",ImageUrl= "http://lorempixel.com/100/100/people/2"  }
            };
            if (String.IsNullOrWhiteSpace(SearchText))
                return _contacts;
            else
              return (ObservableCollection<Contact>)_contacts.Where(c => c.Name.StartsWith(SearchText));[/b]
        }
      

Open in new window



while  implementing search  functionality in contacts I  am  getting error  at  lastline.Code  compiles perfectly while  running  gives error.
If  I  make  return  type  IEnumerable  problem  might get solved  but  delete  contact  functionality  might  not refresh  list.
I  have  attached  xaml and  cs  file  to this  question  ,please  help
ContextListPage.xaml
ContextListPage.xaml.cs
ADITYA RAOSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
What exact error do you get?
0
ADITYA RAOSoftware DeveloperAuthor Commented:
Unhandled Exception:

System.InvalidCastException: Specified cast is not valid. occurred
0
ADITYA RAOSoftware DeveloperAuthor Commented:
0
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Fernando SotoRetiredCommented:
Please post the code where you defined the variable _contacts.
0
ADITYA RAOSoftware DeveloperAuthor Commented:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ContextList.Model;
using System.Collections.ObjectModel;

namespace ContextList
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ContextListPage : ContentPage
    {
        private ObservableCollection<Contact> _contacts;
        public ContextListPage()
        {
            InitializeComponent();

            myContextList.ItemsSource = GetContacts();
        }

        private void CallClicked(object sender, EventArgs e)
        {
            var menuitem = sender as MenuItem;
            var con = menuitem.CommandParameter as Contact;
            DisplayAlert("Call Clicked", con.Name, "OK");
        }

        private void DeleteClicked(object sender, EventArgs e)
        {
            var menuitem = sender as MenuItem;
            var con = menuitem.CommandParameter as Contact;
            _contacts.Remove(con);
        }

        private void myContextList_Refreshing(object sender, EventArgs e)
        {
            myContextList.ItemsSource = GetContacts();
            myContextList.EndRefresh();
        }

        private ObservableCollection<Contact> GetContacts(String SearchText = null)
        {
            _contacts = new ObservableCollection<Contact>
            {
                new Contact{Name = "mosh",Status ="hi",ImageUrl= "http://lorempixel.com/100/100/people/1"  },
                 new Contact{Name = "josh",Status ="halo",ImageUrl= "http://lorempixel.com/100/100/people/2"  }
            };
            if (String.IsNullOrWhiteSpace(SearchText))
                return _contacts;
            else
                return (ObservableCollection<Contact>)_contacts.Where(c => c.Name.StartsWith(SearchText));
        }

        private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            GetContacts(e.NewTextValue);
        }
    }
}

Open in new window

0
ADITYA RAOSoftware DeveloperAuthor Commented:
It  is same file ContextListPage.xaml.cs,please see  see  top 8th line
0
Fernando SotoRetiredCommented:
Hi ADITYA RAO;

As the exception stated you have an invalid cast being thrown. This will happen when the SearchText is not null and the else part of the if statement is taken this is because the query is returning a IEnumerable<Contact> and NOT an ObservableCollection and can not be directly cast to one. Change your if statement as follows.
if (String.IsNullOrWhiteSpace(SearchText))
    return _contacts;
else
    return new ObservableCollection<Contact>(_contacts.Where(c => c.Name.StartsWith(SearchText)));

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ADITYA RAOSoftware DeveloperAuthor Commented:
Thank you very much It  resolved  my  issue
0
Fernando SotoRetiredCommented:
Not a problem Aditya, glad to help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.