如何基于LINQ中的类型对集合进行排序 [英] How to sort a collection based on type in LINQ
问题描述
我有一个这样的收藏
Class Base{}
Class A : Base {}
Class B : Base {}
List<Base> collection = new List<Base>();
collection.Add(new A());
collection.Add(new B());
collection.Add(new A());
collection.Add(new A());
collection.Add(new B());
现在,我想根据类型(A/B)对集合进行排序.我该怎么做?请帮助我.
Now I want to sort the collection based on type (A/B). How I can do this? Please help me.
推荐答案
您可以使用类型信息本身:
You can use the type information itself:
collection.Sort( (a,b) =>
{
bool aType = a.GetType() == typeof(A);
bool bType = b.GetType() == typeof(A);
return aType.CompareTo(bType);
});
这将适用于您指定的两种类型,但不会超出它们.它确实允许您显式指定顺序(即:如果希望在"A"之前使用"B"元素,则可以使用此技术使其生效).
This will work for the two types you specified, but doesn't scale beyond them. It does allow you to specify the order explicitly (ie: if you want "B" elements before "A", you could make it work using this technique).
如果你需要支持多种类型,并且不需要提前指定排序,你可以这样做:
If you need to support many types, and the ordering doesn't need to be specified in advance, you could do something like:
collection.Sort( (a,b) => a.GetType().FullName.CompareTo(b.GetType().FullName) );
这将处理任意数量的类型(即,也包括C和D子类型),并按其完整类型名称对其进行排序.
This would handle any number of types (ie: a C and a D subtype, too), and order them by their full type name.
这篇关于如何基于LINQ中的类型对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!