그래서 왜 당신이 돌아가 첫 번째는"연기를"? 기 때문에 나중에 순서 당신은 같은 단어는"연기를"다시합니다. 왜 당신이 돌아가 첫 번째 항목의"접속"? 기 때문에 나중에 순서에 보이지 않으면 이 단어는 더 이상.
도:반환하는 경우에 단어의 순서는 없이 단어입니다.
이에 쉬운 것입 LINQ,재귀가 있지만,그것은 매우 효율적인:한 모든 단어는 것을 확인하는의 나머지는 순서를 볼 수는 경우는 단어에서 나머지입니다.
그것은 것 방법을 더 효율적으로 기억하는 가장 높은 지수는 단어를 발견.
의 확장으로 방법입니다. 익숙하지 않은 경우 확장자를 가진 방법을 참조하십시오 extension 방법 분석.
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source)
{
return FindLastOccurrences<T>(source, null);
}
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source,
IEqualityComparer<T> comparer)
{
// TODO: check source not null
if (comparer == null) comparer = EqualityComparer<T>.Default;
Dictionary<T, int> dictionary = new Dictionary<T, int>(comparer);
int index = 0;
foreach (T item in source)
{
// did we already see this T? = is this in the dictionary
if (dictionary.TryGetValue(item, out int highestIndex))
{
// we already saw it at index highestIndex.
dictionary[item] = index;
}
else
{
// it is not in the dictionary, we never saw this item.
dictionary.Add(item, index);
}
++index;
}
// return the keys after sorting by value (which contains the highest index)
return dictionay.OrderBy(keyValuePair => keyValuePair.Value)
.Select(keyValuePair => keyValuePair.Key);
}
그래서 모든 항목에 대해 소스 시퀀스에서,우리는지 확인하는 경우 그것은 사전에 있습니다. 하지 않을 경우,우리는 추가 항목으로 키를 사전에 있습니다. 값이 index.
는 경우 그것은 이미 사전에서,다음 값이 최고의 인덱스가 우리는 이 항목을 발견하기 전에. 분명히 현재 지수는 더 높은,그래서 우리는 우리를 교체 가치 사전에 있습니다.
마지막으로 우리는 순서 키의 값 쌍을 사전에 의해 오름차순으로 값을 반환만 키를 사용합니다.