Recursão em conexões

 avatar
unknown
csharp
3 years ago
2.2 kB
8
Indexable
    public class RecursiveRepository
    {
        public List<Elemento> Elementos { get; set; }
        public Dictionary<Elemento, List<Conector>> Conexoes { get; set; } = new Dictionary<Elemento, List<Conector>>();
        public RecursiveRepository(List<Elemento> elementos)
        {
            Elementos = elementos;
        }

        public void GetConectors()
        {
            foreach (var elemento in Elementos)
            {
                GetConectorsRecursively(elemento);
            }
        }

        private void GetConectorsRecursively(Elemento elemento)
        {
            try
            {
                foreach (var conector in elemento.Conectores)
                {
                    GetConectorsRecursively(conector);
                }
                foreach (var con in elemento.Conectores)
                {
                    if (ConectorsConsts.NomesConectores.Contains(con.Name))
                    {
                        if (Conexoes.ContainsKey(elemento))
                        {
                            Conexoes[elemento].Add(con);
                            return;
                        }
                        Conexoes.Add(elemento, new List<Conector> { con });
                    }
                }
                if (elemento.Conectores.Count == 0)
                {
                    return;
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
    }

    public class Elemento
    {
        public string Nome { get; set; }
        public IList<Conector> Conectores { get; set; } = new List<Conector>();

        public override string ToString()
        {
            return Nome;
        }
    }
    public class Conector : Elemento
    {
        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }

    public static class ConectorsConsts
    {
        public static List<string> NomesConectores = new List<string>()
        {
            "Chuveiro",
            "Condicionado",
            "Caixa"
        };
    }
Editor is loading...