.Distinct()
returns distinct values of a list in order, I.e. 1,2,3,1
becomes 1,2,3
.
I want to get the distinct values of a last but always return the last value instead of the first - how would i do that?
var input = new List<string> { "AAA", "BBB", "CCC", "AAA" };
//input = input
// .Distinct()
// .ToList();
// Returns: "AAA", "BBB", "CCC"
//input = input
// .GroupBy(c => c)
// .Select(c => c.OrderByDescending(x => x).Last())
// .ToList();
// Returns: "AAA", "BBB", "CCC"
// TEST
var output = new List<string> { "BBB", "CCC", "AAA" };
if (input.SequenceEqual(output))
{
Console.WriteLine("Success!");
}
else
{
Console.WriteLine("Fail!");
}
CodePudding user response:
As Lasse v. Karlsen pointed out, reversing the string running a distinct and reversing the string again works.
input.Reverse();
input = input
.Distinct()
.Reverse()
.ToList();
Just be mindful that 2 different .Revers()
calls are used: List<T>.Reverse()
and Enumerable.Reverse(source)
(Linq).