通过内部元素对元组内的元素进行排序 [英] Sorting elements inside a tuple by inner elements
问题描述
我有多个数据类型的元组dataframe
I have a tuple dataframe
of multiple data types
public static void Main(string[] args) {
int[] a = { 1, 0, 3, 4, 0};
int[] b = { 3, 0, 9, 10, 0};
int[] c = { 2, 3, 3, 5, 0};
var ret = new Dictionary<string, int[]>();
ret.Add("Jack", a);
ret.Add("Jane", b);
ret.Add("James", c);
var dataframe = new Tuple<string[], Dictionary<string, int[]>, string[]>(
new string[] { "Game 1", "Game 2", "Game 3", "Game 4", "Game 5" },
ret,
new string[] { "A", "B", "C", "B", "A" }
);
dataframe.item1
和dataframe.item3
中的值是dataframe.item2
中字典中各列的不同标签.
我想按dataframe.item3
的字母顺序对元组中的项目进行排序,包括字典中数组的顺序.
The values in dataframe.item1
and dataframe.item3
are different labels for the columns in dictionary in dataframe.item2
.
I want to sort items in the tuple including the order of arrays in the dictionary alphabetically by dataframe.item3
.
所以dataframe.item3
将是{"A","A","B","B","C"}
dataframe.item1
将是{"Game 1","Game 5","Game 2","Game 4","Game 3"}
dataframe.item2["Jack"]
为{1, 0, 0, 4, 3}
这是我尝试过的
//Sorting the dictionary
Dictionary<string, int[]> sortedDict = new Dictionary<string, int[]>();
for each (var item in dataframe.Item2)
{
Array.Sort(dataframe.Item3,dataframe.Item2[item])
}
//Sorting the strings and creating a new dataframe
var sorted_dataframe = new Tuple<string[], Dictionary<string, int[]>, string[]>(
Array.Sort(dataframe.Item3, dataframe.Item1),
sortedDict,
Array.Sort(dataframe.Item3)
);
推荐答案
好吧,我建议将数据复制到另一个更适合排序的结构中:
Well, I would recommend to copy the data to another structure, more suitable for sorting:
游戏{ 姓名 玩家们 代码 }
Game { Name Players Code }
并仅使用Linq的OrderBy(...)
,但是您似乎更喜欢这种结构.如果是这样,并且您可以容忍k*n*log(n)
复杂性,则可以将第三个数组复制到临时缓冲区,然后按此缓冲区的副本对所有数组进行排序:
and just use Linq's OrderBy(...)
, but it looks like you prefer this structure. If so and you can tolerate k*n*log(n)
complexity, you can copy the third array to temporary buffer and then sort all the arrays by copy of this buffer:
var tmp = new string[dataframe.Item3.Length];
Array.Copy(dataframe.Item3, tmp, tmp.Length);
var t = new string[dataframe.Item3.Length];
Array.Copy(tmp, t, t.Length);
Array.Sort(t, dataframe.Item1);
foreach (var v in dataframe.Item2) {
t = new string[dataframe.Item3.Length];
Array.Copy(tmp, t, t.Length);
Array.Sort(t, v.Value);
}
t = new string[dataframe.Item3.Length];
Array.Copy(tmp, t, t.Length);
Array.Sort(t, dataframe.Item3);
但是,我真的建议您遵循第一个方法-将数据复制到更合适的结构中.这样会更快.
However, I really recommend to follow the first one - copy the data to the more appropriate structure. It will be much faster.
这篇关于通过内部元素对元组内的元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!