我有这样的集合,
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());
Run Code Online (Sandbox Code Playgroud)
现在我想根据类型(A/B)对集合进行排序.我怎么能这样做?请帮我.
您可以使用类型信息本身:
collection.Sort( (a,b) =>
{
bool aType = a.GetType() == typeof(A);
bool bType = b.GetType() == typeof(A);
return aType.CompareTo(bType);
});
Run Code Online (Sandbox Code Playgroud)
这适用于您指定的两种类型,但不会扩展到它们之外.它允许您明确指定顺序(即:如果您想要"A"之前的"B"元素,您可以使用此技术使其工作).
如果您需要支持多种类型,并且不需要提前指定排序,您可以执行以下操作:
collection.Sort( (a,b) => a.GetType().FullName.CompareTo(b.GetType().FullName) );
Run Code Online (Sandbox Code Playgroud)
这将处理任意数量的类型(即:C和D子类型),并按其完整类型名称对它们进行排序.
private static int OrderOnType(Base item)
{
if(item is A)
return 0;
if(item is B)
return 1;
return 2;
}
Run Code Online (Sandbox Code Playgroud)
然后从以下选择:
collection.OrderBy(OrderOnType)
Run Code Online (Sandbox Code Playgroud)
要么
collection.Sort((x, y) => OrderOnType(x).CompareTo(OrderOnType(y)));
Run Code Online (Sandbox Code Playgroud)
取决于您是否想要就地排序.如果你真的想要的话,可以将OrderOnType放入lambda中,但这对我来说似乎更具可读性,而且我更喜欢在添加时保留lambdas而不是降低可读性.
collection.OrderBy(i => i.GetType() == typeof(A) ? 0 : 1);
Run Code Online (Sandbox Code Playgroud)
会给你一个包含所有As 然后所有Bs的序列