質問
私はおそらく自分でこれを書くことができますが、私がそれを達成しようとしている特定の方法は私を投げ捨てています。 .NET 3.5で導入された、IEnumerablesのネストされたIEnumerable(など)を取り、それを1つのIEnumerableにフラット化する一般的な拡張メソッドを作成しようとしています。誰にもアイデアはありますか?
具体的には、拡張アルゴリズム自体の構文に問題があるため、平坦化アルゴリズムに取り組むことができます。
解決
うーん...ここに何が欲しいのか正確にわかりませんが、ここに<!> quot; one level <!> quot;オプション:
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;
}
}
}
それがあなたの望むものではない場合、あなたが望むものの署名を提供できますか?ジェネリックフォームを必要とせず、LINQ to XMLコンストラクターが行うようなことをしたいだけであれば、それはかなり簡単です-イテレーターブロックの再帰的な使用は比較的非効率的です。次のようなもの:
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);
}
}
そして、ノードの3レベルの深い階層を取得する方法
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());
}
次のように表示されます:
Node 1, Level 1
Node 6, Level 1
Node 2, Level 2
Node 3, Level 2
Node 4, Level 3
Node 5, Level 3
2番目のテスト:偶数のNodeIdを持つノードのリストを取得します
[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
エラー処理と単一ロジックのアプローチで完全な例を共有すると思いました。
再帰的フラット化は次のように簡単です:
LINQバージョン
public static class IEnumerableExtensions
{
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
return !source.Any() ? source :
source.Concat(
source
.SelectMany(i => selector(i).EmptyIfNull())
.SelectManyRecursive(selector)
);
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
}
非LINQバージョン
public static class IEnumerableExtensions
{
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
foreach (T item in source)
{
yield return item;
var children = selector(item);
if (children == null)
continue;
foreach (T descendant in children.SelectManyRecursive(selector))
{
yield return descendant;
}
}
}
}
設計上の決定
することを決めました:
- null
IEnumerable
のフラット化を禁止します。これは、例外のスローを削除することで変更できます。- 最初のバージョンの
source = source.EmptyIfNull();
の前にreturn
を追加 - 第2バージョンの
if (source != null)
の前にforeach
を追加
- 最初のバージョンの
- セレクターによってnullコレクションを返すことを許可します-この方法で、子リストが空でないことを保証する責任を呼び出し側から削除します。これは次の方法で変更できます。
- 最初のバージョンで
.EmptyIfNull()
を削除-セレクタからnullが返された場合、SelectMany
は失敗することに注意してください - 2番目のバージョンで
if (children == null) continue;
を削除-.Where
はnull <=>パラメーターで失敗することに注意してください
- 最初のバージョンで
- children filter selector パラメーターを渡すのではなく、呼び出し側または children selector 内で<=>句を使用して子をフィルター処理できます。
- どちらのバージョンでも遅延呼び出しであるため、効率には影響しません
- 別のロジックとメソッドを混在させることになるため、ロジックを分離しておくことを好みます
使用例
LightSwitchでこの拡張メソッドを使用して、画面上のすべてのコントロールを取得しています。
public static class ScreenObjectExtensions
{
public static IEnumerable<IContentItemProxy> FindControls(this IScreenObject screen)
{
var model = screen.Details.GetModel();
return model.GetChildItems()
.SelectManyRecursive(c => c.GetChildItems())
.OfType<IContentItemDefinition>()
.Select(c => screen.FindControl(c.Name));
}
}
[SelectMany] [1]の目的はそれではないですか?
enum1.SelectMany(
a => a.SelectMany(
b => b.SelectMany(
c => c.Select(
d => d.Name
)
)
)
);
これは、<! level <!> quot;:
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;
}
}
}
免責事項:C#がわかりません。
Pythonでも同じ:
#!/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
機能:
public static class MyExtentions
{
public static IEnumerable<T> RecursiveSelector<T>(this IEnumerable<T> nodes, Func<T, IEnumerable<T>> selector)
{
if(nodes.Any())
return nodes.Concat(nodes.SelectMany(selector).RecursiveSelector(selector));
return nodes;
}
}
使用法:
var ar = new[]
{
new Node
{
Name = "1",
Chilren = new[]
{
new Node
{
Name = "11",
Children = new[]
{
new Node
{
Name = "111",
}
}
}
}
}
};
var flattened = ar.RecursiveSelector(x => x.Children).ToList();
SelectMany
拡張機能メソッドはすでにこれを行っています。
シーケンスの各要素を投影します IEnumerable <!> lt;(Of <!> lt;(T <!> gt;)<!> gt;)および 結果のシーケンスを平坦化します 1つのシーケンス。
yieldはVBでは使用できず、LINQは遅延実行と簡潔な構文の両方を提供するため、使用することもできます。
<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
ループ、つまりその祖先を指す子がある場合、提供されたすべてのソリューションが壊れるので、最初から実装する必要がありました。私と同じ要件がある場合は、これを見てください(私のソリューションが特別な状況で壊れるかどうかも教えてください):
使用方法:
var flattenlist = rootItem.Flatten(obj => obj.ChildItems, obj => obj.Id)
コード:
public static class Extensions
{
/// <summary>
/// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the
/// items in the data structure regardless of the level of nesting.
/// </summary>
/// <typeparam name="T">Type of the recursive data structure</typeparam>
/// <param name="source">Source element</param>
/// <param name="childrenSelector">a function that returns the children of a given data element of type T</param>
/// <param name="keySelector">a function that returns a key value for each element</param>
/// <returns>a faltten list of all the items within recursive data structure of T</returns>
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Func<T, object> keySelector) where T : class
{
if (source == null)
throw new ArgumentNullException("source");
if (childrenSelector == null)
throw new ArgumentNullException("childrenSelector");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
var stack = new Stack<T>( source);
var dictionary = new Dictionary<object, T>();
while (stack.Any())
{
var currentItem = stack.Pop();
var currentkey = keySelector(currentItem);
if (dictionary.ContainsKey(currentkey) == false)
{
dictionary.Add(currentkey, currentItem);
var children = childrenSelector(currentItem);
if (children != null)
{
foreach (var child in children)
{
stack.Push(child);
}
}
}
yield return currentItem;
}
}
/// <summary>
/// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the
/// items in the data structure regardless of the level of nesting.
/// </summary>
/// <typeparam name="T">Type of the recursive data structure</typeparam>
/// <param name="source">Source element</param>
/// <param name="childrenSelector">a function that returns the children of a given data element of type T</param>
/// <param name="keySelector">a function that returns a key value for each element</param>
/// <returns>a faltten list of all the items within recursive data structure of T</returns>
public static IEnumerable<T> Flatten<T>(this T source,
Func<T, IEnumerable<T>> childrenSelector,
Func<T, object> keySelector) where T: class
{
return Flatten(new [] {source}, childrenSelector, keySelector);
}
}
さて、上記の約3つの回答から組み合わされた別のバージョンがあります。
再帰的。 yieldを使用します。ジェネリック。オプションのフィルター述語。オプションの選択機能。できる限り簡潔にしました。
public static IEnumerable<TNode> Flatten<TNode>(
this IEnumerable<TNode> nodes,
Func<TNode, bool> filterBy = null,
Func<TNode, IEnumerable<TNode>> selectChildren = null
)
{
if (nodes == null) yield break;
if (filterBy != null) nodes = nodes.Where(filterBy);
foreach (var node in nodes)
{
yield return node;
var children = (selectChildren == null)
? node as IEnumerable<TNode>
: selectChildren(node);
if (children == null) continue;
foreach (var child in children.Flatten(filterBy, selectChildren))
{
yield return child;
}
}
}
使用法:
// With filter predicate, with selection function
var flatList = nodes.Flatten(n => n.IsDeleted == false, n => n.Children);
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;
}
}
たぶんこんな感じ?または、潜在的に無限に深い可能性があるということですか?
class PageViewModel {
public IEnumerable<PageViewModel> ChildrenPages { get; set; }
}
Func<IEnumerable<PageViewModel>, IEnumerable<PageViewModel>> concatAll = null;
concatAll = list => list.SelectMany(l => l.ChildrenPages.Any() ?
concatAll(l.ChildrenPages).Union(new[] { l }) : new[] { l });
var allPages = concatAll(source).ToArray();
基本的に、再帰関数の外側にあるマスターIENumerableが必要です。次に、再帰関数(擬似コード)にあります
private void flattenList(IEnumerable<T> list)
{
foreach (T item in list)
{
masterList.Add(item);
if (item.Count > 0)
{
this.flattenList(item);
}
}
}
IEnumerableにネストされたIEnumerableの意味は本当にわかりませんが、その中にあるものは何ですか?ネストのレベルはいくつですか?最終的なタイプは何ですか?明らかに私のコードは正しくありませんが、考えさせられることを願っています。