Reputation: 125
I am learning MVVM Light
and the app I am working on has a functionality to search for event names. Here are my codes for filtering a ListBox
as the user types into TextBox
.
The error is: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<NGO_Volunteer_Comm_Platform_v1._0.DataModel.Event>' to 'System.Collections.Generic.List<NGO_Volunteer_Comm_Platform_v1._0.DataModel.Event>'. An explicit conversion exists (are you missing a cast?)
ViewModel
codes:
private static ObservableCollection<Event> _searchEventCollection = new ObservableCollection<Event>();
public static ObservableCollection<Event> SearchEventCollection
{
get { return _searchEventCollection; }
set { _searchEventCollection = value; }
}
//search from homepage event section
private RelayCommand _eventSearch;
/// <summary>
/// Gets the EventSearch.
/// </summary>
public RelayCommand EventSearch
{
get
{
return _eventSearch
?? (_eventSearch = new RelayCommand(
async () =>
{
SearchEventCollection.Clear();
var eventList = await App.MobileService.GetTable<Event>().ToListAsync();
foreach (Event ename in eventList)
{
SearchEventCollection.Add(new Event
{
Id = ename.Id,
EventName = ename.EventName,
Date = ename.Date,
Location = ename.Location,
Desc = ename.Desc
});
}
}));
}
}
private string filter;
public String Filter
{
get
{
return this.filter;
}
set
{
this.filter = value;
RaisePropertyChanged("SearchEventCollection");
}
}
public List<Event> FilteredNames
{
get
{
return (from name in SearchEventCollection where name.EventName.StartsWith(filter) select name);
}
}
public searchfromhomepageViewModel()
{
filter = "";
}
How do I resolve this error?
Upvotes: 0
Views: 109
Reputation: 292535
Use the ToList
extension method to create a List<T>
from an IEnumerable<T>
:
public List<Event> FilteredNames
{
get
{
return (from name in SearchEventCollection where name.EventName.StartsWith(filter) select name).ToList();
}
}
Or change the type of the FilteredNames
property to IEnumerable<Event>
. Actually, that's probably a better idea. In general, you shouldn't expose concrete collection types publicly, because it doesn't let you return an instance of a different type if you need to change it later. Also, returning a List<T>
seems to imply that you can modify the list. But since a new list is returned each time the property is called, modifying it will have no effect on the property, so it's misleading.
Upvotes: 2