Unable to cast object of type WhereSelectListItera

2020-08-19 02:12发布

I am working on these lists to get an item that matches the selected item from the combobox.

private void InitializaMessageElement()
{
    if (_selectedTransactionWsName != null)
    {
  1. get a transaction webservice name matching the selected item from the drop down here the output=TestWS which is correct

    var getTranTypeWsName = TransactionTypeVModel
         .GetAllTransactionTypes()
         .FirstOrDefault(transTypes => 
                 transTypes.WsMethodName == _selectedTransactionWsName);
    
  2. Loop the list of wsnames from the treenode list. Here it gives me all the node I have which is correct.

    var wsNameList = MessageElementVModel
         .GetAllTreeNodes().Select(ame => 
                 ame.Children).ToList();//. == getTranTypeWsName.WsMethodName);
    
  3. find the getTranTypeWsName.WsMethodName in the wsNameList. Here is where I have the problem:

          var msgElementList = wsNameList.Select(x => x.Where(ame => getTranTypeWsName != null && ame.Name == getTranTypeWsName.WsMethodName)).ToList();
    

my MsgElement list:

    MsgElementObsList = new ObservableCollection<MessageElementViewModel>(msgElementList);
    this.messageElements = _msgElementList;
    NotifyPropertyChanged("MessageElements");
}

Here it is throwing the cast error. why is it not working? I am new to LINQ. thanks

标签: linq
2条回答
我想做一个坏孩纸
2楼-- · 2020-08-19 02:36

Modify

MsgElementObsList = new ObservableCollection<MessageElementViewModel>((List<MessageElementViewModel>) msgElementList);

to

MsgElementObsList = new ObservableCollection<MessageElementViewModel>(msgElementList);

This is because although all lists are enumerable, all enumerables are not lists, and this one happens not to be one.

Also, your bool error has to do with returning true in the select. Here's the fixed code for that:

var msgElementList = wsNameList.Select(x => 
     x.Where(ame => ame.Name == getTranTypeWsName.WsMethodName));
查看更多
【Aperson】
3楼-- · 2020-08-19 02:50

As the error is trying to tell you, LINQ methods return special iterator types the implement IEnumerable<T>; they do not return List<T>.
This enables deferred execution.

Since the object isn't actually a List<T>, you can't cast it to a type that it isn't.

If you need a List<T>, you can either call ToList(), or skip LINQ entirely and use List<T>.ConvertAll(), which is like Select(), but does return List<T>.

查看更多
登录 后发表回答