C# LINQ - 使用 OrderBy EnumValue 和联合结果集对对象列表进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1131584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ - Sort List of objects using OrderBy EnumValue, and Union result set?
提问by
Greetings! I want to use LINQ to query a list of objects and sort them by an enumeration value, string value then union the rest of the list sorted in a similar fashion LINQ newbie here, so be gentle.
你好!我想使用 LINQ 来查询对象列表,并按枚举值、字符串值对它们进行排序,然后合并以类似方式排序的列表的其余部分,这里是 LINQ 新手,所以要温和。
//CTOR for my class
MyClass(id, "Name Value Here", Enum.EnumValueHere);
I create a list of these objects and want to variably sort them such that all items with Enum.EnumValue[X] are shown first in the list, sorted by Name, followed by all other items sorted in a similar fashion (almnost like a Union of result sets in SQL)
我创建了这些对象的列表,并希望对它们进行可变排序,以便 Enum.EnumValue[X] 的所有项目首先显示在列表中,按名称排序,然后是以类似方式排序的所有其他项目(almnost like an Union SQL 中的结果集)
//What I have so far (only sorts the list)
List<MyClass> = (from s in MyClass orderby s.EnumValue, s.NameValue select s).ToList();
Any Guru's out there have some LINQ Magic to share?
有没有大师可以分享一些 LINQ 魔法?
Thanks!
谢谢!
采纳答案by Svish
Not sure exactly what you mean, but could you use something like this?
不确定你的意思,但你能用这样的东西吗?
// Using Color as enum just to make things clearer
class ClassyClass
{
public string Name {get; private set;}
public Color Color {get; private set;}
public ClassyClass(id, string name, Color color) { ... }
}
var orderedList = collectionOfClassyClasses
.OrderBy(x => x.Color != Color.Red) // False comes before true
.ThenBy(x => x.Color)
.ThenBy(x => x.Name)
.ToList();
If collectionOfClassyClasses
was some sort of collection of ClassyClass
objects, then orderedList
would be ordered so that all those with Color set to Red would come first, ordered by name, and then all the others ordered by color and then name. At least I think it would... haven't tested it :p Let me know if it doesn't, hehe.
如果collectionOfClassyClasses
是某种ClassyClass
对象集合,orderedList
则将进行排序,以便所有颜色设置为红色的对象首先出现,按名称排序,然后按颜色和名称排序所有其他对象。至少我认为它会......没有测试过:p 如果没有,请告诉我,呵呵。
回答by yieldvs
You could take the first list and do a list.AddRange() which takes an ienumerable.
您可以采用第一个列表并执行一个 list.AddRange() ,它需要一个可枚举的。