LINQ, ever since its introduction has turned out to be one of the favorite tools for .Net Developers. The post focus on couple of quick recipes for common scenarios.
Scenario 001
You have a collection of objects and you would like verify if the collection is sorted in increasing/decreasing order.
Recipe
We could always sort the collection and compare with the original version, however, if you really want to stick to a LINQ based solution, following extension methods is one approach.
public static bool IsIncreasing<TSource>(this IEnumerable<TSource> data) { return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) < 0).All(b => b); } public static bool IsDecreasing<TSource>(this IEnumerable<TSource> data) { return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) > 0).All(b => b); }
Demo
void Main() { var itemSet1 = new[] {1,3,4,5,6}; var itemSet2 = new[] {5,4,3,2,1}; Console.WriteLine($"Is {nameof(itemSet1)} increasing ? {itemSet1.IsIncreasing()}" ); Console.WriteLine($"Is {nameof(itemSet1)} decreasing ? {itemSet1.IsDecreasing()}" ); Console.WriteLine($"Is {nameof(itemSet2)} increasing ? {itemSet1.IsIncreasing()}" ); Console.WriteLine($"Is {nameof(itemSet2)} decreasing ? {itemSet1.IsDecreasing()}" ); }
Output
Is itemSet1 increasing ? True Is itemSet1 decreasing ? False Is itemSet2 increasing ? True Is itemSet2 decreasing ? False
Scenario 002:
Consider you have a Collection ‘A’. You want to ensure that each element in the series vary in an alternating way, that is, for each element in A, A[i] < A[i+1] > A[i+2] or A[i] > A[i+1] < A[+2]. For example, for the collection {1,3,2,4,3,5} follows the pattern.
Recipe
Once again we will write the solution as an extension method. Well, that’s easier to ‘reuse’ right.
public static bool IsAlternating<TSource>(this IEnumerable<TSource> dataList) { return VerifyIfAlternating(dataList.ToList(),true) || VerifyIfAlternating(dataList.ToList(),false); } private static bool VerifyIfAlternating<TSource>(IList<TSource> data,bool toggle) { return data.Zip(data.Skip(1), (first, second) => { toggle = !toggle; return Comparer.Default.Compare(first,second) > 0 == toggle; }) .All(b=>b); }
Demo
void Main() { var itemSet3 = new[] {1,4,1,4,1}; var itemSet4 = new[] {2,4,3,2,1}; Console.WriteLine($"Is {nameof(itemSet3)} alternating ? {itemSet3.IsAlternating()}" ); Console.WriteLine($"Is {nameof(itemSet4)} alternating ? {itemSet4.IsAlternating()}" ); }
Output
Is itemSet3 alternating ? True Is itemSet4 alternating ? False
That’s it for now. This is one series I would like to continue.