c# - C# 中的排序列表替代项

标签 c# .net list generic-collections

我有很多对象,都来自同一个类(ColorNum)每个对象有 2 个成员变量(m_Color 和 m_Number)

例子:

ColorNum1(Red,25)
ColorNum2(Blue,5)
ColorNum3(Red,11)
ColorNum4(White,25)

这 4 个对象在 ColorNumList 中

List<ColorNum> ColorNumList = new List<ColorNum>();

现在我想对列表进行排序,使 mColor = "Red"的对象位于顶部。 我不关心剩余对象的顺序。

我的谓词方法应该是什么样的?

最佳答案

使用 linq:

var sortedRedAtTop = 
    from col in ColorNumList 
    order by col.Color == Red ? 1 : 2
    select col;

或者列表的排序方式:

ColorNumList.Sort( (x,y) => 
    (x.Color == Red ? 1 : 2)-(y.Color == Red ? 1 : 2) );

关于c# - C# 中的排序列表替代项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1097556/

相关文章:

c# - 如何生成随机字母数字字符串?

.net - 如何测试我的 .NET 客户端正在使用哪个版本的 TLS?

python - 如果字典列表不包含特定值,请检查 python

java - 在我的例子中比较 Set 和 List

c# - 我的 Azure 应用程序配置端点有什么问题?

c# - 在 .net 中人为地创建连接超时错误

c# - 如何在 MVC 4 中显示来自路径的图像?

c# - Process.StandardInput 或从 C# 代码执行的应用程序的编码问题

.net - 黑名单送货地址逻辑

python - 如何从 python 中的现有列表创建列表