-1

What will be the best way to replace:

for(int i=0; i<10; i++) 
{
   if(!members[i].Equals(anotherMembers[i]))
   {
      return false;
   }
}

with LINQ expression?

paparazzo
  • 44,497
  • 23
  • 105
  • 176
inside
  • 3,047
  • 10
  • 49
  • 75
  • 3
    Not really sure, but may be you are looking for [`Enumerable.SequenceEqual`](http://msdn.microsoft.com/en-us/library/vstudio/bb348567(v=vs.100).aspx), like `members.SequenceEqual(anotherMembers)` – Habib Nov 13 '14 at 16:36
  • there has been a long debate about this in LINQ land. See http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet – pm100 Nov 13 '14 at 16:38
  • 2
    @pm100 This is not the same debate since there is no mutation ocuring in this loop. – juharr Nov 13 '14 at 16:42
  • @Habib, that wasn't exact my case, I really simplified the example, so it won't work for me :( – inside Nov 13 '14 at 16:51
  • 1
    @Stanislav Then you haven't adequately described your problem, preventing a meaningful quality answer. – Servy Nov 13 '14 at 17:15

1 Answers1

3

I don't think LINQ would be more readable option, but in general you need to Zip sequences first to be able to deal with pairs at the same index:

var allSame = members.Zip(anotherMemebers, (x,y)=> Tuple.Create(x,y))
       .All(t => t.Item1.Equals(t.Item2)); // or other operation on pairs

As Habib pointed out if you just need to compare sequences SequenceEqual may be better choice.

As @juharr commented .Take(10) may be needed to close match original loop, but LINQ versions are way more forgiving - you'd need to check item count to exactly match all "out of range" errors from original loop.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • ah, that looks good! but good point, it won't make it more readable, I'll go with classic for loop and accept your answer:) – inside Nov 13 '14 at 16:40
  • 3
    I think you need to add `Take(10)` before the `All` to make it exactly the same. Even then it would be different if either collection has less than 10 items (no exception). – juharr Nov 13 '14 at 16:40
  • @juharr - good point on `Take(10)` - inlined comment. Exact match of `for` would look ridiculous in LINQ version - I'd keep `for` OR write LINQ version that matches real requirement rather that possibly incomplete `for`. – Alexei Levenkov Nov 13 '14 at 16:48
  • I think the right answer is: _What will be the best way to replace it to LINQ_ is **NONE** – gdoron Nov 13 '14 at 16:53