C# Get every Nth element in a List

Let’s say you have the following list of objects:

[a1, b2, c3, d4, e5, f6, g7, h8, i9]

Now, say you want to grab every 3rd element inside this list, how would you do that? That is, you want the resulting list to be:

[c3,  f6,  i9]

Here’s a generic List extension algorithm that should help you do so (using C#):

        public static List<T> GetAllNthElements<T>(this List<T> list, int n)
        {
            List<T> result = new List<T>();
            for (int i = (n - 1); i < list.Count; i += n)
            {
                result.Add(list[i]);
            }

            return result;
        }

Explanation:

Let’s use our example from above, where we want every 3rd element inside that list. We’d call the method as:

var everyThirdElementList = theList.GetAllNthElements(3);

By passing it the Nth value as 3, the value of ‘i’ inside the for loop would start off as (n – 1) = (3 – 1) = 2. The second indexed item in the list will be grabbed, which, in this case is ‘c3’. Next, ‘i’ is incremented by n, so we get (i + n) = (2 + 3) = 5. This means the item in the fifth index is taken as well, which is ‘f6’. And so on, and so forth, until ‘i’ is greater than or equal to the list count.

In C#, simply add this under a List Extensions static class and import to whichever class you need this method in.

You way want to improve on this method by handling the following base cases:

  • If n is less than or equal to 0 (might not want to loop, this will cause errors)
  • If n is equal to 1 (you can just return the list that was given)

Xamarin.UITest – Wait for element to be visible

In UI Testing, sometimes you are limited by how fast the UI can process each request or page load. Your tests may have trouble finding UI elements just simply because they haven’t had a chance to load yet. To combat this issue, we need to introduce the “Wait For Element” concept.

In Xamarin.UITest, it is built right into the App class, which we can make use of. An example usage can be seen below:

app.WaitForElement(e => e.Marked(<item>), <timeoutMessage>, TimeSpan.FromSeconds(<timeInSeconds>));

This is great and all, but wouldn’t it get tedious to repeat this every time you needed to wait on something to appear? Why don’t we make things much easier for us by extending the App class with the following method:

    public static void WaitUntilElementIsVisible(this IApp app, string markedId, int timeInSeconds = 3)
    {
        var timeoutMessage = $"UI Test timed out while waiting on {markedId} to appear. (Total wait time: {timeInSeconds} seconds)";
        app.WaitForElement(e => e.Marked(markedId), timeoutMessage, TimeSpan.FromSeconds(timeInSeconds));
    }

Now, you can just simply call WaitUntilElementIsVisible() on the App object and passing in the Marked Id, with the optional timeout which defaults at 3 seconds.

Example usages:

app.WaitUntilElementIsVisible("SomeLabelId"); // Default of 3 second timeout
app.WaitUntilElementIsVisible("SomeLabelId", 10);  // 10 second timeout

C# Get and Set Private fields using Reflection

In C#, we can use reflection to dynamically access private fields from an object. It is especially useful for Unit Testing your code, when you need to check private fields and members, or perform some set-up.

Now I don’t recommend doing this in your prod code, since in most cases, there’s a reason a field is set to private, in order to guarantee access security.

So how do we go about using reflection in C#? In my case, I created a helper class that my Unit Tests use to access private fields. Here is a quick snippet of what that class might look like:

using System.Reflection;

public class FieldAccessHelper
{
    public static object GetField<T>(T obj, string field)
    {
        return typeof(T).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
    }

    public static void SetField<T>(T obj, string field, object value)
    {
        typeof(T).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(obj, value);
    }
}

As seen above, we have two methods, GetField() and SetField().

GetField() takes in the object of type T, along with the string field that you want to access. Just remember to cast the returned object in the calling code.

SetField() takes in the object of type T, along with the string field you want to set, and then the object value itself.

Of course, you can easily add more methods to help access fields, metadata, methods and more through reflection. Highly recommend renaming the file too to be more generic. This should be a good starting point though.

Overall, C# Reflection can be quite useful in helping you set-up Unit Tests, and retrieve values you otherwise wouldn’t have been able to.