Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)
- where TSequence : IEnumerable<TElement>
- {
- foreach (TSequence sequence in sequences)
- {
- foreach(TElement element in sequence)
- {
- yield return element;
- }
- }
- }
- static IEnumerable Flatten(params object[] objects)
- {
- // Can't easily get varargs behaviour with IEnumerable
- return Flatten((IEnumerable) objects);
- }
- static IEnumerable Flatten(IEnumerable enumerable)
- {
- foreach (object element in enumerable)
- {
- IEnumerable candidate = element as IEnumerable;
- if (candidate != null)
- {
- foreach (object nested in candidate)
- {
- yield return nested;
- }
- }
- else
- {
- yield return element;
- }
- }
- }
- /// Traverses an object hierarchy and return a flattened list of elements
- /// based on a predicate.
- ///
- /// TSource: The type of object in your collection.</typeparam>
- /// source: The collection of your topmost TSource objects.</param>
- /// selectorFunction: A predicate for choosing the objects you want.
- /// getChildrenFunction: A function that fetches the child collection from an object.
- /// returns: A flattened list of objects which meet the criteria in selectorFunction.
- public static IEnumerable<TSource> Map<TSource>(
- this IEnumerable<TSource> source,
- Func<TSource, bool> selectorFunction,
- Func<TSource, IEnumerable<TSource>> getChildrenFunction)
- {
- // Add what we have to the stack
- var flattenedList = source.Where(selectorFunction);
- // Go through the input enumerable looking for children,
- // and add those if we have them
- foreach (TSource element in source)
- {
- flattenedList = flattenedList.Concat(
- getChildrenFunction(element).Map(selectorFunction,
- getChildrenFunction)
- );
- }
- return flattenedList;
- }
- class Node
- {
- public int NodeId { get; set; }
- public int LevelId { get; set; }
- public IEnumerable<Node> Children { get; set; }
- public override string ToString()
- {
- return String.Format("Node {0}, Level {1}", this.NodeId, this.LevelId);
- }
- }
- private IEnumerable<Node> GetNodes()
- {
- // Create a 3-level deep hierarchy of nodes
- Node[] nodes = new Node[]
- {
- new Node
- {
- NodeId = 1,
- LevelId = 1,
- Children = new Node[]
- {
- new Node { NodeId = 2, LevelId = 2, Children = new Node[] {} },
- new Node
- {
- NodeId = 3,
- LevelId = 2,
- Children = new Node[]
- {
- new Node { NodeId = 4, LevelId = 3, Children = new Node[] {} },
- new Node { NodeId = 5, LevelId = 3, Children = new Node[] {} }
- }
- }
- }
- },
- new Node { NodeId = 6, LevelId = 1, Children = new Node[] {} }
- };
- return nodes;
- }
- [Test]
- public void Flatten_Nested_Heirachy()
- {
- IEnumerable<Node> nodes = GetNodes();
- var flattenedNodes = nodes.Map(
- p => true,
- (Node n) => { return n.Children; }
- );
- foreach (Node flatNode in flattenedNodes)
- {
- Console.WriteLine(flatNode.ToString());
- }
- // Make sure we only end up with 6 nodes
- Assert.AreEqual(6, flattenedNodes.Count());
- }
- [Test]
- public void Only_Return_Nodes_With_Even_Numbered_Node_IDs()
- {
- IEnumerable<Node> nodes = GetNodes();
- var flattenedNodes = nodes.Map(
- p => (p.NodeId % 2) == 0,
- (Node n) => { return n.Children; }
- );
- foreach (Node flatNode in flattenedNodes)
- {
- Console.WriteLine(flatNode.ToString());
- }
- // Make sure we only end up with 3 nodes
- Assert.AreEqual(3, flattenedNodes.Count());
- }
- Node 6, Level 1
- Node 2, Level 2
- Node 4, Level 3
- enum1.SelectMany(
- a => a.SelectMany(
- b => b.SelectMany(
- c => c.Select(
- d => d.Name
- )
- )
- )
- );
- static IEnumerable Flatten(IEnumerable enumerable)
- {
- foreach (object element in enumerable)
- {
- IEnumerable candidate = element as IEnumerable;
- if (candidate != null)
- {
- foreach (object nested in Flatten(candidate))
- {
- yield return nested;
- }
- }
- else
- {
- yield return element;
- }
- }
- }
- #!/usr/bin/env python
- def flatten(iterable):
- for item in iterable:
- if hasattr(item, '__iter__'):
- for nested in flatten(item):
- yield nested
- else:
- yield item
- if __name__ == '__main__':
- for item in flatten([1,[2, 3, [[4], 5]], 6, [[[7]]], [8]]):
- print(item, end=" ")
- 1 2 3 4 5 6 7 8
- static class EnumerableExtensions
- {
- public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)
- {
- foreach(var child in sequence)
- foreach(var item in child)
- yield return item;
- }
- }
- <Extension()>
- Public Function Flatten(Of T)(ByVal objects As Generic.IEnumerable(Of T), ByVal selector As Func(Of T, Generic.IEnumerable(Of T))) As Generic.IEnumerable(Of T)
- Return objects.Union(objects.SelectMany(selector).Flatten(selector))
- End Function
- private void flattenList(IEnumerable<T> list)
- {
- foreach (T item in list)
- {
- masterList.Add(item);
- if (item.Count > 0)
- {
- this.flattenList(item);
- }
- }
- }
Add Comment
Please, Sign In to add comment