0

So, I create a IList<> Like this.

 private IList<Agent> m_agentCollection = new List<Agent>();

to add 2 value is macdAgent and rsiAgent

 m_agentCollection.Add(macdAgent);
 m_agentCollection.Add(rsiAgent);

but in for-loop part

        for (int i = 0; i < m_agentCollection.Count; i++)
        {
                AgentMACD macdAgent = (AgentMACD)m_agentCollection[i];               
                AgentRSI rsiAgent = (AgentRSI)m_agentCollection[i];
        }

I get a Unable to cast object of type '.AgentMACD ' to type '.AgenRSI'.'.

It's because AgentMACD is on index 0 and AgentRSI is on index 1 and how can i get through with this?

Mac N.
  • 51
  • 7
  • Your list contains to instances of differnt types. You itterate over all items and cast each item to every possible type. This will only work if you''ve only one type and many alias names for it. I assume you've real different types. Try casting each item to a type using `if (m_agentCollection[i] is AgendMACD macdAgent) { /* work with macdAgent */ } else if (m_agentCollection[i] is AgentRSI rsiAgent) { /* work with rsiAgent */ }` – Sebastian Schumann Jul 13 '17 at 05:01
  • You need to check array index, ensure you don't cast with same index: `if (i == 0) { AgentMACD macdAgent = (AgentMACD)m_agentCollection[i]; } else if (i == 1) { AgentRSI rsiAgent = (AgentRSI)m_agentCollection[i]; }` – Tetsuya Yamamoto Jul 13 '17 at 05:01
  • From what I Understand so far, list(0) have AgentMACD and list(1) have AgentRSI and so on. So, just add i++ between them. Simply. – Faraz Sultan Jul 13 '17 at 05:03

3 Answers3

2

You should cast it based on the type the item in the list corresponds to.

Try this:

foreach (var agent in m_agentCollection)
    {
        if (agent is AgentMACD)
        {
            AgentMACD macdAgent = agent as AgentMACD;
        }
        else if (agent is AgentRSI)
        {
            AgentRSI rsiAgent = agent as AgentRSI;
        }
    }
ashin
  • 2,543
  • 1
  • 12
  • 17
2

You can use IEnumerable.OfType method for filtering collection based on the actual type of element.

var macdAgent = agentCollection.OfType<AgentMACD>().FirstOrDefault();
var rsiAgent = agentCollection.OfType<AgentRSI>().FirstOrDefault();
Fabio
  • 31,528
  • 4
  • 33
  • 72
0

Just check of which Type is your current list's element and cast to that type like this:

for (int i = 0; i < m_agentCollection.Count; i++)
{
    if(m_agentCollection[i] is AgentMACD)
    {
         AgentMACD macdAgent = (AgentMACD)m_agentCollection[i];    
    }
    else if(m_agentCollection[i] is AgentRSI)       
    {
         AgentRSI rsiAgent = (AgentRSI)m_agentCollection[i];    
    }
}
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46