如何在列表中分隔值

本文关键字:分隔 列表 | 更新日期: 2023-09-27 18:01:00

我有如下定义的类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 .
    }
   }

如何在列表中分隔值

此处不连接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;

您应该使用SelectMany扩展方法,该方法旨在实现

例如

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

将返回id和符号的扁平列表。