public void RemoveUnnecessaryT() { List <Transition> auxTransitions = new List <Transition>(); foreach (Transition transition in Transitions) { if (transition.Token == null && transition.From != null) { auxTransitions.Add(transition); } } var numberOfStatesTDuplicates = Transitions.GroupBy(u => u.To) .Select(x => new { Count = x.Count(), State = x.Key }).ToList(); foreach (var item in numberOfStatesTDuplicates) { if (item.Count > 1) { auxTransitions = auxTransitions.Where(x => x.To.StateName != item.State.StateName).ToList(); auxTransitions = auxTransitions.Where(x => x.From.StateName != item.State.StateName).ToList(); } } var numberOfStatesFDuplicates = Transitions.GroupBy(u => u.From) .Select(x => new { Count = x.Count(), State = x.Key }).ToList(); foreach (var item in numberOfStatesFDuplicates) { if (item.Count > 1) { auxTransitions = auxTransitions.Where(x => x.From.StateName != item.State.StateName).ToList(); auxTransitions = auxTransitions.Where(x => x.To.StateName != item.State.StateName).ToList(); } } Transition auxFrom; Transition auxTo; foreach (Transition item in auxTransitions) { auxFrom = null; auxTo = null; foreach (Transition transition in Transitions) { if (item.From == transition.From) { auxFrom = transition; } } foreach (Transition transition in Transitions) { if (item.From == transition.To) { auxTo = transition; } } if (auxFrom != null && auxTo != null && auxFrom.From.StateName != "0") { auxTo.To = auxFrom.To; } States.Remove(item.From); Transitions.Remove(item); for (int i = 0; i < States.Count(); i++) { States[i].StateName = i.ToString(); } } }