[英]work with ICollection and IEnumerable<T>
I have some code expecting an ICollection
. 我有一些期待ICollection
代码。 Now I want to devide that collection into smaller chunks by grouping them based on a given attribute (all elements within my collection are instances of an abstract base-class, however for legacy code we do not use the generic version of that interface). 现在,我想通过基于给定的属性将这些集合分组来将其划分为较小的块(集合中的所有元素都是抽象基类的实例,但是对于遗留代码,我们不使用该接口的通用版本)。 So what I´d like to achieve is to obtain any enumerable list of collections (one for every group). 因此,我想要实现的是获取任何可枚举的集合列表(每组一个)。 To get this I planned to convert the ICollection
to the generic IEnumerable<T>
using the Cast<T>
-method on ICollection
, and afterwards build a dictionary from that IEnumerable<T>
using a LINQ-query. 为了得到这个我计划将转换ICollection
到通用IEnumerable<T>
使用Cast<T>
上-方法ICollection
,然后建造一个字典从IEnumerable<T>
使用LINQ查询。 But I fell there might be some better approaches. 但是我认为可能会有更好的方法。 Do you have any? 你有什么?
public override void DoSomething(ICollection features)
{
var grp = features.Cast<MyBaseClass>().GroupBy(x => x.table);
foreach(var g in grp) base.DoSomething(g);
}
EDIT: Hence the base-method (surely) has same signatur (also expects an instance of ICollection
) how do I get the values of the groups back to the (non-generic) ICollection
? 编辑:因此,基本方法(肯定)具有相同的signatur(也需要ICollection
的实例)如何将组的值返回到(非通用) ICollection
?
I don't think there is anything wrong with your approach, but there is one caveat: if the ICollection
instance contains an element that is not of type MyBaseClass
, you'll get a cast exception. 我不认为您的方法有什么问题,但有一个警告:如果ICollection
实例包含的元素不是 MyBaseClass
类型, MyBaseClass
异常。 You can work around this using the OfType
extension method, which checks if the element is actually of the type and if so, it casts it to the target type. 您可以使用OfType
扩展方法来解决此问题,该方法将检查元素是否实际为类型,如果是,则将其强制转换为目标类型。 If the element is of a different type, it is just ignored and no exception is thrown. 如果元素的类型不同,则将其忽略并且不会引发异常。
public override void DoSomething(ICollection features)
{
var grp = features.OfType<MyBaseClass>().GroupBy(x => x.table);
foreach(var g in grp) base.DoSomething((ICollection)g.ToList());
}
You can see a working example here: https://dotnetfiddle.net/0VkedY 您可以在这里看到一个有效的示例: https : //dotnetfiddle.net/0VkedY
Of course, if your requirement is that all elements must be of a specific type, you should use Cast
instead of OfType
. 当然,如果您的要求是所有元素都必须为特定类型,则应使用Cast
而不是OfType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.