LINQ - 组特定类型的类 [英] LINQ - group specific types of classes
问题描述
这个问题类似于<一href="http://stackoverflow.com/questions/2835192/linq-group-one-type-of-item">http://stackoverflow.com/questions/2835192/linq-group-one-type-of-item但在一个更通用的方法来处理。
This question is similar to http://stackoverflow.com/questions/2835192/linq-group-one-type-of-item but handled in a more generic way.
我有一个列表,具有多种派生类。我可能有这样的事情:
I have a List that has various derived classes. I may have something like this:
List<BaseClass> list = new List<BaseClass>() {
new Class1(1),
new Class2(1),
new Class1(2),
new Class3(1),
new Class2(2),
new Class4(1),
new Class3(2)
};
我想使用LINQ到半排序列表,以便自然秩序维持,除了某些类具有base.GroupThisType ==真。所有类与GroupThisType应在该第一类的相同类型的发生地组合在一起。以下是输出应该是这样的:
I am trying to use LINQ to semi-sort the list so that the natural order is maintained EXCEPT for certain classes which have base.GroupThisType == true. All classes with GroupThisType should be grouped together at the place that the first class of the same type occurs. Here is what the output should be like:
List<BaseClass> list = new List<BaseClass>() {
new Class1(1),
new Class1(2),
new Class2(1),
new Class3(1),
new Class3(2)
new Class2(2),
new Class4(1),
};
编辑:哎呀,忘了说这个结果是假设(1类和3类).GroupThisType ==真
Oops, forgot to say this result is assuming (Class1 and Class3).GroupThisType == true
推荐答案
这样的:
list = list.Select((o, i) => new { Index = i * 10000, Value = o })
.GroupBy(q => q.GetType())
.SelectMany(g => {
if (g.First().GroupThisType)
return g.Select((q, i) =>
new { Index = g.First().Index + i, Value = q.Value }
);
else
return g;
})
.OrderBy(q => q.Index)
.Select(q => q.Value)
.ToList();
在 I * 10000
允许多达10,000项从一组被任何两个项目之间插入。
The i * 10000
allows up to 10,000 items from a group to be inserted between any two items.
您可以替换 g.First()。GroupThisType
与 typesToGroup.Contains(g.Key)
。
这篇关于LINQ - 组特定类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!