-
Notifications
You must be signed in to change notification settings - Fork 5
/
Interview - JPL (part 2).linq
66 lines (56 loc) · 1.65 KB
/
Interview - JPL (part 2).linq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<Query Kind="Program">
<NuGetReference>MoreLinq</NuGetReference>
<Namespace>MoreLinq</Namespace>
</Query>
void Main()
{
var tree = new []
{
new MyMeta
{
UniqueId = "item-1-1",
Children = new []
{
new MyMeta { UniqueId = "item-2-1" },
new MyMeta { UniqueId = "item-2-2" },
new MyMeta
{
UniqueId = "item-2-3",
Children = new[]
{
new MyMeta { UniqueId = "item-3-1" },
new MyMeta { UniqueId = "item-3-2" },
}
},
}
},
new MyMeta { UniqueId = "item-1-2" },
};
tree.Flatten(i => i.Children).Select(i =>i.UniqueId).Dump();
}
public static class IEnumerableOfTExtensions
{
public static IEnumerable<TSource> Flatten<TSource>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TSource>> childGetter)
{
if (source == null) return Enumerable.Empty<TSource>();
var flattenedList = new List<TSource>(source);
source.ForEach(i =>
{
var children = childGetter(i);
if (children != null) flattenedList.AddRange(children.Flatten(childGetter));
});
return flattenedList;
}
}
class MyMeta
{
public MyMeta() { }
public MyMeta(IEnumerable<MyMeta> children)
{
children.ForEach(i=> i.Parent = this);
this.Children = children;
}
public IEnumerable<MyMeta> Children { get; set;}
public MyMeta Parent { get; set;}
public string UniqueId { get; set;}
}