【发布时间】:2016-12-17 16:32:11
【问题描述】:
我有一个 Root-Parent-Child 二叉树,需要根据几个标准求和并获取子值。我不确定是使用 Linq 还是遍历树。 Linq 查询崩溃(Additional information: Unable to cast object of type 'ID' to type 'Greek'),我不知道如何遍历树并检查每个参数。感谢您提供任何帮助,或链接到网站和书籍以增加我的知识。这个link 有帮助,但我仍然卡住了。
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;
}
}
}
}
}
}
}
【问题讨论】:
-
据我所知,您根本不使用二叉树。您只需填充您的节点,并将它们添加到您的列表中。你确定你想要一些像遍历的树吗?或者您也只是不知道如何遍历列表?
-
你是对的......我如何遍历列表?
-
这不是二叉树,而是n叉树。
-
你说得对,谢谢指正
标签: c# linq binary-tree