我想按值的频率对列表进行排序并区分它 c#
I want to sort a list by frequency of values and distinct it c#
我有一个整数列表,例如
List<int> Lst = {1,1,1,2,2,3,3,3,4,4}
我希望这个列表是
Lst = {1,3,2,4}
(按值的频率排序且不同,因此 1 排在第一位,
3 后 2 后 4
感谢您的帮助:D
我正在做一个项目,我有一个这样的列表,我需要重新排列它
我还没有尝试用代码让它工作,因为我想不出让它工作的方法
我希望函数的输出是一个排列成 {1,3,2,4} 的列表
谢谢 :D
使用 Linq 相当简单 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)
:创建一个包含 4 个组的列表。每个组都有一个键,它是数字,值是组的成员。所以你会有类似 { 1: [1, 1, 1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4] }
OrderByDescending(x => x.Count())
:按组中的项目数对组进行排序,最大的组在前。所以你得到 { 1: [1, 1, 1], 3: [3, 3, 3], 2: [2, 2], 4: [4, 4] }
Select(x => x.Key)
:从每组中取出钥匙,得到[1, 3, 2, 4]
ToList()
: 把它全部变成一个列表
如果有两组具有相同数量的项目——在您的示例中,有三个 1 和三个 3——那么这将按照它们在输入中出现的顺序对它们进行排序(所以,在这里,输出是 [1, 3, 2, 4]
,因为输入中 1 在 3 之前。
这是因为ordering behaviour of GroupBy
(见备注):
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.
以及 OrderByDescending
is stable 这一事实(再次参见备注),因此如果两个项目比较相等,则它们的顺序将被保留。
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.
我有一个整数列表,例如
List<int> Lst = {1,1,1,2,2,3,3,3,4,4}
我希望这个列表是
Lst = {1,3,2,4}
(按值的频率排序且不同,因此 1 排在第一位, 3 后 2 后 4 感谢您的帮助:D
我正在做一个项目,我有一个这样的列表,我需要重新排列它
我还没有尝试用代码让它工作,因为我想不出让它工作的方法
我希望函数的输出是一个排列成 {1,3,2,4} 的列表 谢谢 :D
使用 Linq 相当简单 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)
:创建一个包含 4 个组的列表。每个组都有一个键,它是数字,值是组的成员。所以你会有类似{ 1: [1, 1, 1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4] }
OrderByDescending(x => x.Count())
:按组中的项目数对组进行排序,最大的组在前。所以你得到{ 1: [1, 1, 1], 3: [3, 3, 3], 2: [2, 2], 4: [4, 4] }
Select(x => x.Key)
:从每组中取出钥匙,得到[1, 3, 2, 4]
ToList()
: 把它全部变成一个列表
如果有两组具有相同数量的项目——在您的示例中,有三个 1 和三个 3——那么这将按照它们在输入中出现的顺序对它们进行排序(所以,在这里,输出是 [1, 3, 2, 4]
,因为输入中 1 在 3 之前。
这是因为ordering behaviour of GroupBy
(见备注):
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.
以及 OrderByDescending
is stable 这一事实(再次参见备注),因此如果两个项目比较相等,则它们的顺序将被保留。
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.