将内容数量有限的字符串数组内容从最后一个数组位置传输到新的字符串数组

时间:2019-01-05 08:38:02

标签: c# arrays string c#-4.0 c#-3.0

我有一个名为“ string_array_packet”的字符串数组,其中包含

FA,6,52,4C,0,A4,FA,6,52,4C,0,A4,FA,6,52,4C,0,A4,FA,6,52,4C,0,A4 ,FA,6,52,4C,0,A4,FA,6,52,4C,0,A4,FA,6,52,4C,0,A4,FA,6,

现在,我需要检查从Array(string_array_packet)的末尾到另一个字符串array的内容“ FA,6,52,4C,0,A4,”(这是正确的响应)的存在。在上面的数组内容中,正确的响应从string_array_packet [Length-8]开始,考虑到FA是每个响应的起始字节。但由于数组内容是动态生成的,因此索引位置可能会有所不同。我正在尝试以下操作,但我知道如果位置发生变化,它将不起作用。任何帮助将不胜感激

    string_array_packet[string_array_packet.Length - 8]);

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作。

var strArray = new string[]{"FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6","52","4C","0","A4","FA","6"};
var searchArray = new string[]{"FA","6","52","4C","0","A4"};
var index = strArray.FindAllIndexOf("FA")
                    .Reverse() 
                    .First(x=>strArray
                                .Skip(x)
                                .Take(searchArray.Count())
                                .SequenceEqual(searchArray));
var result = strArray.Skip(index).Take(searchArray.Count());

其中FindAllIndexOf定义为

public static class Extension
{
    public static int[] FindAllIndexOf<T>(this IEnumerable<T> values, T val)
    {
        return values.Select((b,i) => object.Equals(b, val) ? i : -1)
                     .Where(i => i != -1)
                     .ToArray();
    }
}

这将输出为

index : 36
result : FA,6,52,4C,0,A4