对对象 [] 内的字符串 [] 子数组进行排序

本文关键字:数组 排序 对象 字符串 | 更新日期: 2023-09-27 18:17:55

我有以下类:

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是一个对象,因为必须能够容纳任何类型的数组,每次它都包含许多字符串或 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

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

对对象 [] 内的字符串 [] 子数组进行排序

好吧,在您编辑的情况下,只需测试是否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

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

        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