gpt4 book ai didi

c# - 以特殊格式对字符串数组进行排序

转载 作者:行者123 更新时间:2023-11-30 19:38:47 25 4
gpt4 key购买 nike

它需要将这样的string 数组排序为特殊格式。我们的数组是:

input1 = new string[12]{"Active1","12","mm","Active2","17","mm","Width","25","mil","Height","20","mil"}  

我们想要的排序列表是:

sort = new string[6]{"Serial","Width","Height","Active1","Active2","Time"}  

我的有效输出格式是这样的:

Output = [{Serial,null,null},{Width,25,mil},{Height,20,mil},{Active1,12,mm},{Active2,17,mm},{Time,null,null}]

对于Input数组中不存在的数据,需要设置null值。

我将此代码用于我的目的:

var Output = (from i in Enumerable.Range(0, input.Length / 3)
let index = Array.IndexOf(sort, input[i * 3])
where index >= 0
select ne3w string[] { input[i * 3], input[i * 3 + 1] , input[i * 3 + 2]})
.OrderBy(a => Array.IndexOf(sort, a[0])).ToArray();

但它不会显示input 数组中不存在的值。

最佳答案

我会把它放在一个单独的方法中:

private static IEnumerable<string[]> TransformInput(string[] input)
{
return from key in new[] { "Serial", "Width", "Height", "Active1", "Active2", "Time" }
let keyIndex = Array.IndexOf(input, key)
let hasData = keyIndex > 1
select new[]
{
key,
hasData ? input[keyIndex + 1] : null,
hasData ? input[keyIndex + 2] : null
};
}

然后按如下方式使用它:

var input1 = new string[12]   
{ "Active1", "12", "mm", "Active2", "17", "mm", "Width", "25", "mil", "Height", "20", "mil" };

var sorted = TransformInput(input1);

关于c# - 以特殊格式对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com