在对象[]内对string []的子数组进行排序

时间:2015-10-16 08:53:28

标签: c# .net arrays

我有以下课程:

private class st_flow {
    public string[] title;
    public object[] details;               

    public st_flow() {
        title= new string[0]; details = new object[0];
    }
}

我的st_flow.details包含一个字符串数组,我不知道数组的大小,它可以是从string[5]string[15]的任何地方我的问题是我想对这些数组进行排序。在某些情况下,我希望对st_flow.details[0].mystring[6]进行排序,而在其他情况下则对不同的索引进行排序。

编辑:我会尝试解释并回答每个人的评论;我的st_flow.details是一个对象,因为它必须能够容纳任何类型的数组,每次它包含许多类型为string或int等的数组,但从不组合类型。所以在我的代码中我有这样的东西:

st_flow flow = new st_flow();
string[] content = new string[15];
flow.details = new object[15];
//...
// here I fill my content and each time add it to flow
// this part is inside a loop that each time reset the 
// content and add it to flow incrementing the index
//...
flow.details[index] = content;

此时,在程序之外,我们将flow.details承载一个未指定数量的数组,每个数组都具有未知大小。我们实际上并不关心任何一个的大小。想象:

// this contains a content[15] string array which [4] value is 50
flow.details[0]; 
// this also contains a content[15] string arraym with [4] value 80
flow.details[1]; 
// i need to sort on this element and be able to do it both DESC or ASC

我需要根据(例如)flow.details的值(列)对content[4]进行排序,无论它是字符串还是int,而不管数组大小如何。希望这能澄清我的问题,谢谢。

2 个答案:

答案 0 :(得分:1)

好吧,在已编辑的案例中,只需测试为String[]并排序:

  Object[] details = new Object[] {
    123, 
    new String[] {"x", "a", "y"},       // This String[] array
    "bla-bla-bla",
    new String[] {"e", "f", "d", "a"},  // and this one will be sorted
  };

...

  foreach (var item in details) {
    String[] array = item as String[];

    if (null != array)  
      Array.Sort(array);
  }

...

 // Test: print out sorted String[] within details
 Console.Write(String.Join(Environment.NewLine, details
    .OfType<String[]>()
    .Select(item => String.Join(", ", item))));

测试输出是(找到并排序了两个字符串数组)

  a, x, y
  a, d, e, f

答案 1 :(得分:0)

我认为我已经解决了这个问题,仍在测试它是否适用于所有情况:

        public class flow_dt : DataTable { 
            public flow_dt(string[] columns) {
                this.Clear();
                foreach (string s in columns) {
                    this.Columns.Add(s, typeof(string));
                }
            }            
        }

这样我就可以将标题和数据放在一个单独的元素中,而不再使用数组,我可以更轻松地对其进行排序甚至过滤,因为我还在测试它

编辑:在这种情况下,我无法按照以下方式对其进行排序:

            DataView dv = flow.DefaultView;
            dv.Sort = "total DESC";
            flow = (flow_dt)dv.ToTable();

我收到错误,因为无法执行强制转换,我不明白为什么因为我的类继承了DataTable类型。

编辑2 :这是排序部分的解决方案:http://bytes.com/topic/visual-basic-net/insights/890896-how-add-sortable-functionallity-datatable

相关问题