C# 在对象[]内对字符串[]的子数组排序
我有以下课程:C# 在对象[]内对字符串[]的子数组排序,c#,.net,arrays,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\u flow.details包含一个字符串数组,我不知道数组的大小,它可以是string[5]到string
private class st_flow {
public string[] title;
public object[] details;
public st_flow() {
title= new string[0]; details = new object[0];
}
}
我的st\u flow.details
包含一个字符串数组,我不知道数组的大小,它可以是string[5]
到string[15]
我的问题是我想对这些数组进行排序。在某些情况下,我希望根据st\u flow.details[0].mystring[6]
进行排序,而在其他情况下,我希望根据不同的索引进行排序
编辑:我将尝试解释并回答每个人的评论;myst_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;
DataView dv = flow.DefaultView;
dv.Sort = "total DESC";
flow = (flow_dt)dv.ToTable();
此时,在这个过程之外,我们将拥有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
我需要对我的流进行排序。详细信息
取决于(例如)内容[4]
的值(列),而不管它是字符串还是int,也不管数组大小。希望这能澄清我的问题,谢谢。好吧,在您编辑的案例中,只需测试为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
};
我认为我已经解决了这个问题,仍然在测试它是否适用于所有情况:
public class flow_dt : DataTable {
public flow_dt(string[] columns) {
this.Clear();
foreach (string s in columns) {
this.Columns.Add(s, typeof(string));
}
}
}
通过这种方式,我将标题和数据放在一个元素中,不再使用数组,我可以更轻松地对其进行排序甚至过滤,正如我所说的,我仍在测试它
编辑:在这种情况下,我无法对其进行如下排序:
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;
DataView dv = flow.DefaultView;
dv.Sort = "total DESC";
flow = (flow_dt)dv.ToTable();
我得到一个错误,因为无法执行强制转换,我不明白为什么,因为我的类继承自DataTable类型
编辑2:这是排序部分的解决方案:但是。。。。您不能对单个元素进行排序。您要对哪个集合进行排序,并基于什么?
在某些情况下,我希望根据st_flow进行排序。详细信息[0]。mystring[6]
-这没有多大意义details[0]
只是一个对象
,它没有属性mystring
。即使它做到了,我们如何“排序”呢?public stats(){
看起来像一个构造函数,但我们在类st_flow
:一个打字错误?为什么详细信息
和对象[]
?将其存储为具有属性的实类型mystring
,请遵循.NET命名和。如果st\u flow.details
包含字符串数组,它不应该是string[]
类型而不是object[]
?哦,如果x
是某种数组类型,例如string[]
,您可以通过x.length
找到它的长度。因为我可以通过这种方式承载任何类型的数组,请阅读我的编辑,谢谢。是的,请查看我的解决方案是否可行,并解决使用类而不是标准对象的问题。
DataView dv = flow.DefaultView;
dv.Sort = "total DESC";
flow = (flow_dt)dv.ToTable();