【问题标题】:Error An explicit conversion exists C#, MVVM Light - LINQ错误存在显式转换 C#,MVVM Light - LINQ
【发布时间】:2015-07-26 10:51:23
【问题描述】:

我正在学习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?)

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

如何解决此错误?

【问题讨论】:

    标签: c# linq windows-phone-8.1 mvvm-light


    【解决方案1】:

    使用ToList 扩展方法从IEnumerable&lt;T&gt; 创建List&lt;T&gt;

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

    或者将FilteredNames属性的类型改为IEnumerable&lt;Event&gt;。实际上,这可能是一个更好的主意。一般来说,您不应该公开具体的集合类型,因为如果您以后需要更改它,它不会让您返回不同类型的实例。此外,返回 List&lt;T&gt; 似乎意味着您可以修改列表。但是由于每次调用属性都会返回一个新的列表,修改它不会对属性产生影响,所以会产生误导。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      相关资源
      最近更新 更多