开发者

Search for combination of two items with Linq

I previously used the following code to find the first occurrence of a text in a string.

int index = myString.IndexOf("AB");

Now I will change the software so it will look for first occurrence of the two bytes in a List. Is it possible to do with Linq?

Edit

The program purpose is to communicate via the serial port. Previously the program managed data with a string. But it are strange to handle binary data in开发者_运维问答 a string. So I change the program so that data is handled in a List<byte> instead.


Pure LINQ:

var arr = new byte[] { 1, 2, 3, 4, 5, 6 };

var res = arr.Zip(arr.Skip(1), (a, b) => new { a, b }).Select((x, i) => new { x, i })
    .FirstOrDefault(v => v.x.a == 3 && v.x.b == 4);


if (res != null)
{
    Console.WriteLine(res.i);
}


Given how you said you want to search for bytes in a list, I'm assuming you have an object of List<byte>, named list, and a byte[], named bytes.

List<byte> list = new List<byte>();
byte[] bytes = { 0x01, 0x02 };

list.Where((b, i) => (list.Count() >= i + 1 ? false : (b == bytes[0] && list[i + 1] == bytes[1]))).First();

The ternary expression ensures you don't have an ArrayOutOfBoundsException

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜