Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq

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

like image 769
Ayda Sayed Avatar asked Jun 17 '13 15:06

Ayda Sayed


1 Answers

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>.

like image 185
SLaks Avatar answered Oct 20 '22 02:10

SLaks