具有五个数字级别的分层大纲 - 如何插入兄弟或子行并调整现有记录?

问题描述 投票:1回答:1

我有一个带有“点”(或概述)层次结构的表:字段是L1 L2 L3 L4 L5(L =级别)

例如:

1.0.0.0.0 1.1.0.0.0 1.1.1.0.0 1.1.2.0.0 1.2.0.0.0

如果我想在1.1.1.0.0插入一个兄弟,我应该得到一个新的1.1.2.0.0行 - 并且已经存在的1.1.2.0.0应该调整到1.1.3.0.0等。

如果我想插入一个子1.1.1.0.0,我应该得到一个新的1.1.1.1.0行,不需要调整,因为该级别没有兄弟姐妹。

我已经为此创建了程序代码 - 但它变成了意大利面条 - 我希望有一个OOP解决方案,其中包含一个处理这些插入和调整的类。

任何人都可以推荐甚至伪代码来处理这两种类型的插入,并需要调整已经存在的“行”?

任何帮助或建议将不胜感激!

c# oop document hierarchy outlining
1个回答
1
投票

给你评论的人我不认为真的理解这个问题。您已经拥有一个表,因此使用LinkedList除了表之外不会做任何事情。你真的需要传递方法一行插入和一个要插入的字段。只添加值为1.1.1.0.0的新行不能提供足够的重新编号信息。

我在下面的代码中使用了DataTable,每列都有一个Field。简单地编写代码我假设索引是整数。代码不是很复杂

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Outlining outling = new Outlining();
            outling.Add(2,2);
            outling.Add(0, 2);
            outling.Add(5, 2);
        }
    }
    public class Outlining
    {
        public DataTable dt = null;

        public Outlining()
        {
            dt = new DataTable();
            dt.Columns.Add("L1", typeof(int));
            dt.Columns.Add("L2", typeof(int));
            dt.Columns.Add("L3", typeof(int));
            dt.Columns.Add("L4", typeof(int));
            dt.Columns.Add("L5", typeof(int));

            dt.Rows.Add(new object[] { 1, 0, 0, 0, 0 });
            dt.Rows.Add(new object[] { 1, 1, 0, 0, 0 });
            dt.Rows.Add(new object[] { 1, 1, 1, 0, 0 });
            dt.Rows.Add(new object[] { 1, 2, 0, 0, 0 });
        }
        public void Add(int at, int level)
        {
            DataRow newRow = dt.Rows.Add();
            if (at < dt.Rows.Count - 1)
            {
                //move row if not last row
                dt.Rows.Remove(newRow);
                dt.Rows.InsertAt(newRow, at);
            }
            newRow.BeginEdit();
            newRow.ItemArray = dt.Rows[at + 1].ItemArray.Select(x => (object)x).ToArray();
            newRow.EndEdit();

            Renumber(at, level);
        }
        public void Renumber(int rowInsertIndex, int level)
        {
            for (int row = rowInsertIndex; row < dt.Rows.Count - 1; row++)
            {
                Boolean match = true;
                //check if columns to left still match, if no we are done
                for (int i = 0; i < level - 1; i++)
                {
                    if (dt.Rows[i][level] != dt.Rows[i + 1][level])
                    {
                        match = false;
                        break;
                    }
                }
                if (!match) break;
                dt.Rows[row + 1][level] = ((int)(dt.Rows[row + 1][level])) + 1;
            }
        }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.