本文介绍了你如何创建一个基于多个IEnumerables的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想操作的类提供类型为 IEnumerable< X> IEnumerable< Y> 的getter,其中X& Y是基类型T的子类。我想遍历将它们作为类型T处理的内容。是否有方便的方式将它们连接成可以看作 IEnumerable< T>例如:

  IEnumerable< HeaderPart> code $?



; headers = templateFile.MainDocumentPart.HeaderParts;
IEnumerable< FooterPart> footers = templateFile.MainDocumentPart.FooterParts;
列表< OpenXmlPart> result = new List< OpenXmlPart>();
result.Concat< OpenXmlPart>(footers);

HeaderPart和FooterPart都是OpenXmlPart的子类,但是第三行失败:

请注意,我无法更改任何源数据,我需要创建一个新的集合 - 实际上我想要做一个 foreach


解决方案

您可以使用Cast函数将 IEnumerable< ; X> IEnumerable< T> ,然后 Concat / b>

类似于:

  listB.Cast< A>()。 Concat(listC.Cast< A>())


A class I want to operate on provides getters of type IEnumerable<X> and IEnumerable<Y> where X & Y are subclasses of base type T. I want to iterate over the contents of both treating them as type T. Is there a handy way to concatenate both into something which can be seen as IEnumerable<T>?

Example:

        IEnumerable<HeaderPart> headers = templateFile.MainDocumentPart.HeaderParts;
        IEnumerable<FooterPart> footers = templateFile.MainDocumentPart.FooterParts;
        List<OpenXmlPart> result = new List<OpenXmlPart>();
        result.Concat<OpenXmlPart>(footers);

HeaderPart and FooterPart are both subclasses of OpenXmlPart but the 3rd line fails:

Note, I can't change either of the source data, I need to create a new collection - actually I want to do a foreach over it.

解决方案

You can use the Cast function to convert IEnumerable<X> to IEnumerable<T> and then Concat to append the second series

Something like:

listB.Cast<A>().Concat(listC.Cast<A>())

这篇关于你如何创建一个基于多个IEnumerables的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:28