对数据库中的数据进行排序和分类

时间:2017-05-06 17:15:46

标签: c# sql sorting oracledb

我需要一种方法来对来自数据库的大量(大约120或更多值)数据进行分类。没有什么想到的,所以我决定在这里问。我需要C#SQL解决方案(或至少提示)。

当前需要排序的数据在一列中,但我对任何建议持开放态度。下面是一个数据示例:

- A2-11 (Main branch that contains all A2 from below)
- A2-113
- A2-114
- A2-115
- .
- .
- .
- F-L-5 (Main branch)
- F-L-55 (Another branch in there)
- F-L-56 (Contains all values below)
- F-L-566 
- F-L-567
- .
- .
- .

先谢谢!!

可以显示为小树图:

TreeExample

3 个答案:

答案 0 :(得分:0)

也许使用Hierarchyid? 大卫

答案 1 :(得分:0)

尝试自定义OrderBy

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


namespace ConsoleApplication50
{
    class Program
    {

        static void Main(string[] args)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("Category", typeof(string));


            string[] data =  { "Main-A2-11", "Main-A2-113", "Main-A2-114", "Main-A2-115",
                              "Third-F-L-56", "Third-F-L-566", "Third-F-L-567",
                              "Second-F-L-5", "Second-F-L-55"
                            };

            foreach (string d in data)
            {
                dt.Rows.Add(new object[] { d });
            }

            dt = dt.AsEnumerable().GroupBy(x => x.Field<string>("Category").Contains("-") ? 
                     x.Field<string>("Category").Substring(0,x.Field<string>("Category").IndexOf("-")) :
                     x.Field<string>("Category"))
                .Select(x => x.OrderBy(y => new SortRecord(y,"Category"))).SelectMany(x => x).CopyToDataTable();

        }
    }
    public class SortRecord : IComparer<SortRecord >, IComparable<SortRecord>
    {
        string[] rowSplitArray;
        int length = 0;
        public SortRecord(DataRow x, string name)
        {
            rowSplitArray = x.Field<string>(name).Split(new char[] { '-' });
            length = rowSplitArray.Length;
        }


        public int Compare(SortRecord  rowA, SortRecord rowB)
        {

            int len = Math.Min(rowA.length, rowB.length);

            for (int i = 0; i < len; i++)
            {
                if (rowA.rowSplitArray[i] != rowB.rowSplitArray[i])
                    return rowA.rowSplitArray[i].CompareTo(rowB.rowSplitArray[i]);
            }

            return rowA.length.CompareTo(rowB.length);

        }
        public int CompareTo(SortRecord row)
        {
            return Compare(this, row);
        }
    }

}

答案 2 :(得分:0)

实现结果有多种方法,但如果您还需要决定性能,请按照本文进行操作。What are the options for storing hierarchical data in a relational database?

你当然可以在sql中使用hierarchyid。 https://docs.microsoft.com/en-us/sql/relational-databases/hierarchical-data-sql-server

This可能对我有帮助。