Revision a8a1636c-1c2b-4c05-a23e-c448e4d7ed1e - Code Review Stack Exchange

First, let's define a method to figure out whether a list follows another list order:

 public static bool IsValidOrder<T>(this IEnumerable<T> items, IEnumerable<T> order)
 {
 IEnumerator<T> orderEnumerator = order.GetEnumerator();
 orderEnumerator.MoveNext();
 return items.All(item => orderEnumerator.ReadUntilGet(item));
 }

 public static bool ReadUntilGet<T>(this IEnumerator<T> enumerator, T item)
 {
 return enumerator.Current.Equals(item) ||
 (enumerator.MoveNext() && enumerator.ReadUntilGet(item));
 }

The `ReadUntilGet<T>` method check if the current is equals to the T item, if it is not it moves the enumerator to the next position and calls itself recursively until it finds the T item, then it returns true. If it reaches the end of the enumerator without finding the T item, it returns false.

The LINQ `All<T>` method check if all elements of a sequence satisfy a condition. Since we call the `ReadUntilGet<T>` method inside the condition, it is called on each item from the list. And the enumerator moves on each new item on the list. If it return false in any of them, the All method return false.

Since the animals can contain names which string representation is not equal to a enum identifier it's better to use strings to define the order, as [@Mat'sMug][1] pointed out.

We can define the order in a list. Notice that numbers indicating the order are not needed because the order of the list is guaranteed to remain the same (the `IEnumerable<T>` interface just iterates, it does not change ordering, AFAIK. At [this answer][2] it's said otherwise, would you care to explain? I don't have enough reputation to comment):

 public static IEnumerable<string> AnimalOrder { get; } = new List<string>
 {
 "Cat",
 "Horse",
 "Dog",
 "Elephant",
 "Great white shark"
 };

So, your method would be:

 public bool ValidateAnimalOrder(List<string> listOfAnimals)
 {
 return listOfAnimals.IsValidOrder(AnimalOrder);
 }

Note that this method iterate just once on both lists and returns as soon as possible (because the `All` method returns on the first item that doesn't match).


 [1]: https://codereview.stackexchange.com/questions/142533/validate-the-order-of-a-liststring-by-custom-strings/142541#comment267352_142565
 [2]: https://codereview.stackexchange.com/a/142541/112524

AltStyle によって変換されたページ (->オリジナル) /