gpt4 book ai didi

.net - 在 LINQ 查询中获取当前枚举器(迭代器?)。就像 for 循环中的当前索引一样

转载 作者:行者123 更新时间:2023-12-03 00:13:26 24 4
gpt4 key购买 nike

是否可以在 LINQ 查询中获取当前枚举器(...或迭代器?不知道哪一个是正确的)?

例如,我尝试创建所有当前加载的程序集的 XML 输出(通过 LINQ to XML)。

Dim xmldoc As XDocument = New XDocument(
New XElement("Types",
Assembly.GetExecutingAssembly().GetReferencedAssemblies() _
.Select(Function(name) Assembly.Load(name)) _
.SelectMany(Function(assembly) assembly.GetTypes()) _
.Select(Function(type) New XElement("Type", type.FullName))))

输出看起来像这样。

<Types>
<Type>System.Object</Type>
<Type>FXAssembly</Type>
<Type>ThisAssembly</Type>
<Type>AssemblyRef</Type>
<Type>System.Runtime.Serialization.ISerializable</Type>
<Type>System.Runtime.InteropServices._Exception</Type>
.....
</Types>

是否有可能以某种方式从 LINQ 的 Selects 中获取当前的“索引”(计数器?)?我想在 XML 中使用它

<Types>
<Type ID="1">System.Object</Type>
<Type ID="2">FXAssembly</Type>
<Type ID="3">ThisAssembly</Type>
<Type ID="4">AssemblyRef</Type>
<Type ID="or-some-other-unique-id-#5">System.Runtime.Serialization.ISerializable</Type>
.....
</Types>

最佳答案

是的 - 您只需要使用 overload of Select which takes a Func<TSource, int, TResult> 。所以在 C# 中它会是这样的:

XDocument doc = new XDocument(new XElement("Types",
Assembly.GetExecutingAssembly().GetReferencedAssemblies()
.Select(name => Assembly.Load(name))
.SelectMany(assembly => assembly.GetTypes())
.Select((type, index) => new XElement("Type",
new XAttribute("ID", index + 1),
type.FullName))));

抱歉,它不是用 VB 编写的,但它更可能以这种方式工作 - 希望您能完成翻译:)

关于.net - 在 LINQ 查询中获取当前枚举器(迭代器?)。就像 for 循环中的当前索引一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7489414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com