2

I can roll a method, pseudo:

bool Compare(IList left, int lIndex, IList right, int rIndex, int num) { for(int i=0;i<num;++i) { if(left[lIndex+i] != right[rIndex+i]) { return false; } } return true; } 

So given L =[1,2,3,4,5,6,7,8] and R = [5,6,7,8,9] : Compare(L,5,R,1,3) == true

I feel I should be able to do a simple LINQ version but I am not sure how to handle the indexing. Can it be written as a trivial LINQ/lambda... otherwise I'll pull this out as a utility method.


By the way there is a question with a very similar title but it is asking a different thing: https://stackoverflow.com/questions/33812323/compare-two-arrays-using-linq

1
  • Not at a compiler, but something like Left.Skip(3).Intersect(Right.Skip(1).Take(4))).Count() == 4 Commented Apr 15, 2020 at 14:00

2 Answers 2

7

You can Skip, Take, and SequenceEqual:

return left.Skip(lIndex).Take(num).SequenceEqual( right.Skip(rIndex).Take(num)) 

Note that you should make your Compare method generic and use the generic IList<T> instead.

Sign up to request clarification or add additional context in comments.

5 Comments

That's neat, thanks. It doesn't matter in my case but does this end up allocating new objects or does each operation return some sort of palce-holder to the original object?
@Mr.Boy It does create new objects that implement IEnumerable, although no new lists are created. They are basically a "view" on your original list. So I would expect this to have more overhead than your for loop.
OK but we're talking very light-weight objects designed for this kind of use... so I can live with that. Thankyou.
You should keep in mind that it'll work only with generic IList<T>, OP example uses non-generic IList
@PavelAnikhouski my code is pseudo but thanks for pointing this out
0

you can try this

 int num = 3,lIndex =5,rIndex =1; var L = (new List<int>(){1,2,3,4,5,6,7,8}).Skip(lIndex).Take(num).ToList(); var R = (new List<int>(){5,6,7,8,9}).Skip(rIndex).Take(num).ToList(); var result = L.Count() == R.Count() && !R.Except(L).Any() && !L.Except(R).Any() && string.Join(",",L).Equals(string.Join(",",R)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.