fiftyplus
fiftyplus

Reputation: 561

How to use Contains(Of T)(T) method?

I have a byte list variable which I store byte array information here:

internal List<Byte> portBuffer = new List<Byte>();

And I have another byte array variable:

byte[] ret_bytes = { 0x4F, 0x4B };

How can I find out if ret_bytes is inside the portBuffer? The code below seems like not correct.

portBuffer.Contains(ret_bytes)

Another question, how to find out the position of the first element of ret_bytes in side the portBuffer list if it is inside the list?

Thanks

Upvotes: 0

Views: 131

Answers (3)

David
David

Reputation: 1153

Use LINQ - IEnumerable<T>.Intersect(IEnumerable<T>) to get the set of bytes that appear in both portBuffer and ret_bytes.

var portBuffer = new List<Byte> {0x4F, 0x4B, 0x27};
byte[] ret_bytes = { 0x4F, 0x4B, 0x26 };

return portBuffer.Intersect(ret_bytes); // This will return { 0x4F, 0x4B }

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67075

I believe that you are correct in your comments, and this has actually already been asked on SO. Can you please verify this is what you are asking :)

How do I use LINQ Contains(string[]) instead of Contains(string)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500145

Contains doesn't find one sequence within another, it finds one element within a sequence - I don't believe there's anything within .NET which will do what you want out of the box.

It's up to you whether you write a very general purpose implementation or one that just solves your current issue - the former is likely to be more work, but may pay dividends in the long run.

If you only need to find two bytes, I'd be tempted to just iterate:

for (int i = 0; i < list.Count - 1; i++)
{
    if (list[i] == 0x4f && list[i + 1] == 0x4b)
    {
        // Got it
    }
}

Upvotes: 1

Related Questions