Last active
December 19, 2015 20:29
-
-
Save markusjohnsson/6013785 to your computer and use it in GitHub Desktop.
LINQ meta operator. Wraps each element in a meta object also containing the index in the sequence and whether the element is first and if it is last in the sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MetaElement<T> | |
{ | |
public MetaElement(T value, bool isLast, bool isFirst, int index) | |
{ | |
this.Value = value; | |
this.IsLast = isLast; | |
this.IsFirst = isFirst; | |
this.Index = index; | |
} | |
public int Index { get; private set; } | |
public bool IsFirst { get; private set; } | |
public bool IsLast { get; private set; } | |
public T Value { get; private set; } | |
} | |
public static class Ex | |
{ | |
public static IEnumerable<MetaElement<T>> Meta<T>(this IEnumerable<T> source) | |
{ | |
using (var etor = source.GetEnumerator()) | |
{ | |
if (false == etor.MoveNext()) | |
yield break; | |
var isFirst = true; | |
var lastValue = etor.Current; | |
int index = 0; | |
while (etor.MoveNext()) | |
{ | |
yield return new MetaElement<T>(lastValue, isLast: false, isFirst: isFirst, index: index); | |
isFirst = false; | |
lastValue = etor.Current; | |
index++; | |
} | |
yield return new MetaElement<T>(lastValue, isLast: true, isFirst: isFirst, index: index); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment