我需要创建一个新序列(最好使用 linq)来列出一个类型及其实现的所有接口(interface)。
这是一个例子:
public interface ITypeA { }
public interface ITypeB { }
public interface ITypeC { }
public class Class1 { }
public class Class2 : ITypeA, ITypeB, ITypeC { }
public class Class3 : ITypeC, ITypeA { }
var specializedContents = new object[] { new Class1(), new Class2(), new Class3() };
我正在尝试制作一个看起来像这样的序列。
------------------------------------------------------
| Type | Interface |
------------------------------------------------------
| Class2 | ITypeA |
| Class2 | ITypeB |
| Class2 | ITypeC |
| Class3 | ITypeC |
| Class3 | ITypeA |
------------------------------------------------------
我知道我需要对第一列使用 [instance].GetType()
,对第二列使用 [instance].GetType().GetInterfaces()
列,但我无法弄清楚如何展开第一列并使其与第二列对齐。我看了很多,但我只能找到将序列包装到内部列表中的方法,但找不到将预先存在的序列展开到外部列表中的方法。
我查看了 .SelectMany() 方法(来自 this post),感觉我在正确的轨道上,但我似乎无法弄清楚如何使查询正常工作。
那么,如何使用 LINQ 制作这种类型的列表?
最佳答案
使用这个:
from x in specializedContents
let t = x.GetType()
from i in t.GetInterfaces()
select new { Type = t.Name, Interface = i.Name };
关于c# - LINQ - 展平嵌套序列,使其与父序列连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390016/