繁体   English   中英

错误存在显式转换C#,MVVM Light-LINQ

[英]Error An explicit conversion exists C#, MVVM Light - LINQ

我正在学习MVVM Light ,正在使用的应用程序具有搜索事件名称的功能。 这是我用于在用户键入TextBox过滤ListBox代码。 错误是: 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?) 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代码:

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 = "";
}

如何解决此错误?

使用ToList扩展方法从IEnumerable<T>创建List<T> IEnumerable<T>

public List<Event> FilteredNames
{
    get
    {
        return (from name in SearchEventCollection where name.EventName.StartsWith(filter) select name).ToList();
    }
}

或将FilteredNames属性的类型更改为IEnumerable<Event> 实际上,这可能是一个更好的主意。 通常,您不应公开公开具体的集合类型,因为如果以后需要更改它,则不允许您返回其他类型的实例。 另外,返回List<T>似乎意味着您可以修改列表。 但是,由于每次调用该属性都会返回一个新列表,因此对其进行修改不会对该属性产生任何影响,因此会产生误导。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM