Introduction
This tip describes an IEnumerable
extension method that allows you to select an item at its index modulo Count()
.
Using the Code
Given an object enumerable
that implements IEnumerable<T>
, you can use the following extension method ElementAtModCount
to select an item from this object in the sense that:
enumerable.ElementAtModCount(i) = enumerable.ElementAtModCount(i mod Count)
This extension method is given as follows:
using System.Collections.Generic;
using System.Linq;
namespace CodeProject.Articles.EnumerableExtensions
{
public static class EnumerableExtensions
{
public static T ElementAtModCount<T>(this IEnumerable<T> enumerable, int index)
{
var count = enumerable.Count();
var indexModCount = ((index % count) + count) % count;
return enumerable.ElementAt(indexModCount);
}
}
}
An example of how to use this is given as follows:
using CodeProject.Articles.EnumerableExtensions;
using System;
using System.Collections.Generic;
namespace CodeProject
{
class Program
{
static void Main(string[] args)
{
var list =
new List<string>()
{ "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
Console.WriteLine(string.Format(
"It is Monday today, and in 365 days it will be {0}",
list.ElementAtModCount(365)));
Console.WriteLine(string.Format(
"It is Monday today, and three days ago it was {0}",
list.ElementAtModCount(-3)));
Console.ReadLine();
}
}
}