Unable to pass an object of type WhereSelectListIterator 2 System.Collections.Generic.List

I am working on these lists to get an item that matches the selected item from the drop-down list.

private void InitializaMessageElement() { if (_selectedTransactionWsName != null) { 
  • get the webservice transaction name corresponding to the selected element from the drop-down list here output = TestWS, which is correct

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

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

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

my list of MsgElement:

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

Here he throws a cast error. why doesn't it work? I am new to LINQ. thanks

+6
source share
2 answers

As the error tries to tell you, LINQ methods return special iterator types to implement IEnumerable<T> ; they are not returned List<T> .
This allows you to delay execution.

Since the object is not actually List<T> , you cannot distinguish it from a type that is not.

If you need List<T> , you can call ToList() or skip LINQ completely and use List<T>.ConvertAll() , which is similar to Select() but returns List<T> .

+14
source

Edit

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

to

 MsgElementObsList = new ObservableCollection<MessageElementViewModel>(msgElementList); 

This is because although all lists are listed, all lists listed are not , and this one cannot be one.

Also, your bool error is related to returning true in select. Here is the fixed code for this:

 var msgElementList = wsNameList.Select(x => x.Where(ame => ame.Name == getTranTypeWsName.WsMethodName)); 
0
source

Source: https://habr.com/ru/post/947482/


All Articles