Pergunta

Eu provavelmente poderia escrever isso mesmo, mas a forma específica que eu estou tentando fazer é me jogando fora. Eu estou tentando escrever um método de extensão genérica semelhante aos outros introduzidas no .NET 3.5 que vai demorar um IEnumerable aninhada de IEnumerables (e assim por diante) e alise-o em um IEnumerable. Alguém tem alguma idéia?

Especificamente, eu estou tendo problemas com a sintaxe do próprio método de extensão para que eu possa trabalhar em um algoritmo de achatamento.

Foi útil?

Solução

Hmm ... Eu não tenho certeza exatamente o que você quer aqui, mas é aqui uma opção de "um nível":

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;
        }
    }
}

Se não é isso que você quer, você poderia fornecer a assinatura que você quer? Se você não precisa de uma forma genérica, e você só quer fazer o tipo de coisa que LINQ to XML construtores fazer, que é razoavelmente simples - embora o uso recursivo de iterador blocos é relativamente ineficiente. Algo como:

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;
        }
    }
}

Note que que irá tratar uma string como uma sequência de caracteres, no entanto -. Você pode querer cordas de caso de especial para ser elementos individuais em vez de achatamento-los, dependendo do seu caso de uso

Isso ajuda?

Outras dicas

Aqui está uma extensão que pode ajudar. Ele irá percorrer todos os nós na hierarquia de objetos e escolher os que correspondem a um critério. Assume-se que cada objeto na hierarquia de tem uma propriedade de coleção que mantém seus objetos filho.

Eis a extensão:

/// 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;
}

Exemplos (Unidade de testes):

Em primeiro lugar, precisamos de um objeto e uma hierarquia objeto aninhado.

A classe do nó simples

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);
  }
}

E um método para obter um profundo hierarquia de 3 níveis de nós

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;
}

Primeiro Teste: achatar a hierarquia, nenhuma filtragem

[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());
}

Isto irá mostrar:

Node 1, Level 1
Node 6, Level 1
Node 2, Level 2
Node 3, Level 2
Node 4, Level 3
Node 5, Level 3

Segundo Teste: Obter uma lista de nós que têm uma NodeId de número par

[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());
}

Isto irá mostrar:

Node 6, Level 1
Node 2, Level 2
Node 4, Level 3

Eu pensei que eu iria partilhar um exemplo completo com tratamento de erros e uma apporoach-lógica única.

recursiva achatamento é tão simples como:

versão 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>();
    }
}

versão Não-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;
            }
        }
    }
}

As decisões de design

Eu decidi:

  • disallow achatamento de um IEnumerable nulo, isso pode ser alterado através da remoção de arremesso exceção e:
    • acrescentando source = source.EmptyIfNull(); antes return na 1ª versão
    • acrescentando if (source != null) antes foreach na 2ª versão
  • permitem o retorno de uma coleção nula pelo selector - desta forma eu estou removendo a responsabilidade do chamador para assegurar a lista de crianças não estiver vazia, isso pode ser alterado por:
    • remoção .EmptyIfNull() na primeira versão - nota que SelectMany falhará se nulo é devolvido pelo selector
    • remoção if (children == null) continue; na segunda versão - nota que foreach irá falhar em um nulo IEnumerable parâmetro
  • permitir filtragem crianças com cláusula .Where no lado do chamador ou dentro do crianças selector vez de passar um seletor de filtro de crianças parâmetro:
    • não terá impacto sobre a eficiência, porque em ambas as versões é uma chamada adiada
    • seria misturar uma outra lógica com o método e eu prefiro manter a lógica separado

uso Amostra

Estou usando este método de extensão em LightSwitch para se obter todos os controles na tela:

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));
    }
}

Não é isso que [SelectMany] [1] é para?

enum1.SelectMany(
    a => a.SelectMany(
        b => b.SelectMany(
            c => c.Select(
                d => d.Name
            )
        )
    )
);

Aqui está uma versão modificada de Jon Skeet resposta para permitir mais do que "um nível":

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;
        }
    }
}

IMPORTANTE:. Não sei C #

O mesmo em 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=" ")

Ela imprime:

1 2 3 4 5 6 7 8 

Função:

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;
    } 
}

Uso:

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();

O href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx" rel="nofollow noreferrer"> SelectMany método de extensão

Projectos cada elemento de uma sequência de um IEnumerable <(Of <(T>)>) e nivela as sequências resultantes em uma sequência.

Desde rendimento não está disponível em VB e LINQ fornece tanto a execução diferida e uma sintaxe concisa, você também pode usar.

<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

Eu tive de implementar a minha a partir do zero porque todas as soluções fornecidas iria quebrar, caso haja um loop ou seja, uma criança que aponta para seu antepassado. Se você tem os mesmos requisitos que o meu favor, dê uma olhada neste (também deixe-me saber se a minha solução iria quebrar em quaisquer circunstâncias especiais):

Como usar:

var flattenlist = rootItem.Flatten(obj => obj.ChildItems, obj => obj.Id)

Código:

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);
        }
    }

Ok, aqui vai uma outra versão que é combinado de cerca de 3 respostas acima.

recursiva. rendimento de utilizações. Genérico. predicado de filtro opcional. função de seleção opcional. Sobre o mais conciso como eu poderia fazê-lo.

    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;
            }
        }
    }

Uso:

// 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;
    }
}

Talvez assim? Ou você quer dizer que ele poderia ser potencialmente infintly profundo?

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();

Basicamente, você precisa ter um mestre IEnumerable que está fora de sua função recursiva, em seguida, em sua função recursiva (Pseudo-código)

private void flattenList(IEnumerable<T> list)
{
    foreach (T item in list)
    {
        masterList.Add(item);

        if (item.Count > 0)
        {
            this.flattenList(item);
        }
    }
}

Embora eu não tenho certeza do que você quer dizer com IEnumerable aninhado em um IEnumerable ... o que está dentro que? Quantos níveis de aninhamento? Qual é o tipo de final? obviamente, o meu código não está correto, mas eu espero que você fica pensando.

scroll top