c# - LINQ - 展平嵌套序列,使其与父序列连接

标签 c# linq

我需要创建一个新序列(最好使用 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/

相关文章:

c# - ASP.net Identity SecurityStampValidator OnValidateIdentity regenerateIdentity 参数

c# - 弹出窗口替代 Windows Phone 8.0

c# - 渲染特殊字符 C#

mysql - C# SQL Linq 获取所有重复项

c# - 查询不返回任何东西

c# - 将字符串解析为 C# lambda Func

c# - 在 Linq 中使用分组创建字典(字典)

c# - 无论如何使 IList.Contains() 更像通配符包含?

c# - 什么是统一类型系统?

c# - 如何在 LINQ 中选择查询时存储变量?