I have a Root-Parent-Child binary tree and need to sum and get the child values based on several criteria. I'm not sure whether to use Linq or traverse through the tree. The Linq queries crash (Additional information: Unable to cast object of type 'ID' to type 'Greek'
) and I don't know how to traverse through the tree and check each parameter. Thanks for any help, or links to sites & books to increase my knowledge. This link helped but I'm still stuck.
public class Node
{
public List<Node> Children = new List<Node>();
public Node Parent = null;
public Node(Node fromParent = null)
{
if (fromParent != null)
{
Parent = fromParent;
fromParent.Children.Add(this);
}
}
}
public class ID : Node
{
public int IdNo;
public int DealNo;
public string Strategy;
public ID(int _ID,int _DealNo,string _Strategy) : base(null)
{
IdNo = _ID;
DealNo = _DealNo;
Strategy = _Strategy;
}
}
public class Greek : Node
{
public string LegOrPos;
public string GreekType;
public Greek(string _LegOrPos, string _GreekType, Node fromParent = null) : base(fromParent)
{
LegOrPos = _LegOrPos;
GreekType = _GreekType;
}
}
public class DataPoint : Node
{
public int DpNo;
public double Value;
public DataPoint(int _DpNo, double _Value, Node fromParent = null) : base(fromParent)
{
DpNo = _DpNo;
Value = _Value;
}
}
public void SimpleTest()
{
List<Node> MC = new List<Node>();
// 1st node
var oID = new ID(23, 2,"Fly"); // ID,DealNo,Strategy
var oGreek = new Greek("Leg", "Delta", oID); //LegOrPos,GreekType
var oDP = new DataPoint(14, 0.235, oGreek); //DpNo,Value
MC.Add(oID);
// 2nd node
oID = new ID(25, 5,"BWB");
oGreek = new Greek("Leg", "Vega", oID);
oDP = new DataPoint(16, 0.345, oGreek);
MC.Add(oID);
// 3rd node
oID = new ID(31,2,"Fly");
oGreek = new Greek("Leg", "Delta", oID);
oDP = new DataPoint(14, 0.456, oGreek);
MC.Add(oID);
// use linq or traverse through tree?
// get total for several parameters
var Total = MC.Where(x => ((ID)x).DealNo == 2 && ((ID)x).Strategy == "Fly" && ((Greek)x).GreekType == "Delta" && ((DataPoint)x).DpNo == 14) // should sum 1st and 3rd nodes
.SelectMany(x => x.Children)
.Sum(x => ((DataPoint)x).Value);
// get specific value
var Val = Convert.ToDouble(MC.Where(x => ((ID)x).IdNo == 23 && ((Greek)x).GreekType == "Delta" && ((DataPoint)x).DpNo == 14) // should find 1st node
.SelectMany(x => x.Children)
.Select(x => ((DataPoint)x).Value).Single());
// traverse method
foreach (var objID in MC)
{
if (objID.IdNo == 23) //compile error-IdNo not found
{
foreach (Greek objGreek in objID.Children)
{
if (objGreek.GreekType == "Delta")
{
foreach (DataPoint objDP in objGreek.Children)
{
if (objDP.DpNo == 14)
{
double qVal = objDP.Value;
}
}
}
}
}
}
}