Monthly Archives: December 2015

LINQ, C# and Unity…

Having never ‘learned’ c#, the LINQ syntax sometimes escapes me, and it takes a bit of getting used to, but honestly, it’s worth the price of admission!  I recently needed to find the first object in a list whose Y value was greater than another Y value (basically making sure it was on screen).

My first thought was to use a foreach loop, with a break and a bool flag along with a var to store the index like so:

       bool found = false;
       int rowIndex = 0;

                foreach (float y in rowYPos)
                    if (y>scrollOffset)
                        found = true;

This code works, and will return the index of the first entry that exceeds scrollOffset;

However, with LINQ all that becomes:

            int firstRowIndex = rowYPos.FindIndex(x=>x>scrollOffset);

Much shorter, less local vars and pretty self-explanatory.  I didn’t benchmark it to see which was faster, though my hope is that the LinQ method would be, It’s not something that happens often enough to make it a worry.

Handy tip: You’ll need to add a using System.Linq; to the start of the file…