Skip to content

Instantly share code, notes, and snippets.

@elranu
Last active September 28, 2018 22:09
Show Gist options
  • Save elranu/85e8dd9f3a57ed0f1d437c092446839b to your computer and use it in GitHub Desktop.
Save elranu/85e8dd9f3a57ed0f1d437c092446839b to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Extensions
{
public static class IEnumerableExtensions
{
/// <summary>
/// Flats to one level an IEnumrable
/// </summary>
/// <typeparam name="T">any type</typeparam>
/// <param name="rootLevel">The main IEnumerable to flat</param>
/// <returns>Returns the flattend IEnumerable</returns>
public static IEnumerable<object> Flatten<T>(this IEnumerable<T> rootLevel)
{
List<object> flatted = new List<object>();
FlatLevel(flatted, rootLevel);
return flatted;
}
private static void FlatLevel(List<object> mainIEnumerable, IEnumerable currentLevel)
{
foreach (var item in currentLevel ?? Enumerable.Empty<object>())
{
IEnumerable enumerable = item as IEnumerable;
if (enumerable != null)
{
FlatLevel(mainIEnumerable, enumerable);
}
else
{
mainIEnumerable.Add(item);
}
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Extensions;
using System.Collections.Generic;
using System.Linq;
namespace UnitTestProject1
{
[TestClass]
public class TestIEnumerableExtensions
{
[TestMethod]
public void TestFlatten()
{
var list1 = new List<object> { new List<object> { 1, 2, new List<object> { 3 }, 4 } };
CollectionAssert.AreEqual(list1.Flatten().ToList(), new List<object> { 1, 2, 3, 4 });
List<object> list2 = null;
CollectionAssert.AreEqual(list2.Flatten().ToList(), new List<object>());
var list3 = new List<object> { new List<object> { 1, 2, new List<int> { 3, 4 }, 5 } };
CollectionAssert.AreEqual(list3.Flatten().ToList(), new List<object> { 1, 2, 3, 4, 5 });
var list4 = new List<object> { new List<object> { 1, 2, new int[] { 3, 4 }, 5 } };
CollectionAssert.AreEqual(list4.Flatten().ToList(), new List<object> { 1, 2, 3, 4, 5 });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment