I have a list of integers, for example
List<int> Lst = {1,1,1,2,2,3,3,3,4,4}
I want this list to be
Lst = {1,3,2,4}
(sorted by frequency of values and distinct so 1 is first and 3 after and 2 after and then 4 Thanks for the help :D
Im working on a project and I have a list that comes like this and I need to rearrange it
I havent try to make it work with a code yet because I cant think of a way to make it work
I expect the output of the function to be a list that arranged like {1,3,2,4} Thanks :D
Fairly easy with Linq's GroupBy
:
var input = new [] {1,1,1,2,2,3,3,3,4,4};
var output = input.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(x => x.Key)
.ToList();
GroupBy(x => x)
: Creates a list of 4 groups. Each group has a key which is the number, and values which are the members of the group. So you'll have something like { 1: [1, 1, 1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4] }
OrderByDescending(x => x.Count())
: order the groups by the number of items in the group, with the largest group first. So you get { 1: [1, 1, 1], 3: [3, 3, 3], 2: [2, 2], 4: [4, 4] }
Select(x => x.Key)
: Take the key from each group, so you get [1, 3, 2, 4]
ToList()
: turn it all into a listIf there are two groups with equal numbers of items -- in your example, there are three 1's and three 3's -- then this will sort them in the order that they appeared in the input (so, here, the output is [1, 3, 2, 4]
, because 1 comes before 3 in the input).
This is because of the ordering behaviour of GroupBy
(see Remarks):
The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source.
and the fact that OrderByDescending
is stable (again, see the Remarks), so if two items compare equally their order is preserved).
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.