C#-按属性排序 [英] C# - sorting by a property
问题描述
我试图通过自定义属性对C#中的对象集合进行排序. (就上下文而言,我正在使用Twitterizer库使用Twitter API,将直接消息"排序到对话视图中)
I am trying to sort a collection of objects in C# by a custom property. (For context, I am working with the Twitter API using the Twitterizer library, sorting Direct Messages into conversation view)
假设自定义类具有名为label
的属性,其中label
是在类构造函数时分配的string
.
Say a custom class has a property named label
, where label
is a string
that is assigned when the class constructor.
我有所述类的Collection
(或List
没关系),我想根据值将它们全部分类为单独的List
s(或Collection
s) label
并将它们分组在一起.
I have a Collection
(or a List
, it doesn't matter) of said classes, and I want to sort them all into separate List
s (or Collection
s) based on the value of label
, and group them together.
目前,我一直在通过使用foreach
循环并以这种方式检查值来进行此操作-我知道这是浪费CPU时间和糟糕的编程.我为此感到羞耻.
At the moment I've been doing this by using a foreach
loop and checking the values that way - a horrible waste of CPU time and awful programming, I know. I'm ashamed of it.
基本上,我知道我所拥有的所有数据都已提供给我,而且我也知道它应该非常容易排序.一个人用纸做起来很容易,但是我只是不知道如何用C#来做.
Basically I know that all of the data I have is there given to me, and I also know that it should be really easy to sort. It's easy enough for a human to do it with bits of paper, but I just don't know how to do it in C#.
有人对此有解决方案吗?如果您需要更多信息和/或上下文,请询问.
Does anyone have the solution to this? If you need more information and/or context just ask.
推荐答案
您是否尝试过Linq
的这仍然会循环遍历值进行排序-无法解决.这样至少可以清理您的代码.
This is still going to loop through the values to sort - there's no way around that. This will at least clean up your code.
这篇关于C#-按属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!