如何分隔列表中的值

时间:2014-04-30 11:53:10

标签: c#

我有以下类Node定义:

class Node
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Operator { get; set; }
        public string Sign { get; set; }
        public Node Parent { get; set; }
        public IList<Node> Children { get; set; }
        public Node()
        {
            Children = new List<Node>();
        }
        public override string ToString()
        {
            return "Node: " + Operator + " " + Id + " "
            + string.Join(",", Children.Select(x => string.Format("({0}, {1})", x.Sign, x.Id)));
        }
}

如何分别获取SignId?我尝试了以下代码:

var map = new Dictionary<int, Node>();
foreach (var pair in foo)
{
  string body = "";
  Identifier = pair.Value.Id;
  scope = getScope(Convert.ToString(Identifier));
  var flattenedList = pair.Value.Children.Select(x => x.Sign+x.Id).ToList();

  for (int i = 0; i < flattenedList.Count - 1; i++)
    {
         body = body + flattenedList[i].ToString;//Here I am looking to get separately sign and Id for further treatment .
    }

   }

2 个答案:

答案 0 :(得分:0)

而不是在这里连接SignId

var flattenedList = pair.Value.Children.Select(x => x.Sign+x.Id).ToList();

选择节点本身:

var flattenedList = pair.Value.Children.ToList();

然后,在循环内部,您可以单独访问SignId

var sign = flattenedList[i].Sign;
var id = flattenedList[i].Id;

答案 1 :(得分:0)

您应该使用专为此目的而设计的SelectMany扩展方法

e.g。

var flist = pair.Value.Children.SelectMany(x => x.Children, (n, c) => new { n.Id, c.Sign });

将返回id和sign的平面列表。