Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Created March 19, 2018 16:29
Show Gist options
  • Save EgorBo/b041acc81cec1eb85405fa15cf4c37f6 to your computer and use it in GitHub Desktop.
Save EgorBo/b041acc81cec1eb85405fa15cf4c37f6 to your computer and use it in GitHub Desktop.
yield bug.cs
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine(MyLinqTest.LinqTest.Test());
}
}
namespace MyLinqTest
{
public class Slot
{
public readonly string Id;
public Item ContainedItem;
public Slot(string id)
{
Id = id;
}
public IEnumerable<Item> Items => ContainedItem == null ? new Item[0] : new[] {ContainedItem};
}
public class Item
{
public readonly Slot[] Slots;
public Item(Slot[] slots)
{
Slots = slots;
}
}
public static class LinqExtensions
{
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T, IEnumerable<T>> f)
{
return e.Concat(e.SelectMany(c => f(c).Flatten(f)));
}
}
public static class LinqTest
{
static IEnumerable<Slot> GetSlots()
{
yield return new Slot("a");
yield return new Slot("b");
yield return new Slot("c");
yield return new Slot("d");
yield return new Slot("e");
yield return new Slot("f");
yield return new Slot("g") {
ContainedItem = new Item(new[] {
new Slot("x"),
new Slot("y")
})
};
}
public static string Test()
{
var slots = GetSlots().Concat(new[] { new Slot("j") });
var containers = slots
.Flatten(container =>
container.Items.SelectMany(x => x.Slots)
).ToArray();
return string.Join(", ", containers.Select(x => x == null ? "NULL" : x.Id).ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment