2011-09-20 17 views
6

是否有可能在LINQ查询中获取当前Enumerator(...或迭代器?不知道哪个tern是正确的)?在LINQ查询中获取当前枚举数(iterator?)。像循环中的当前索引

例如,我尝试创建所有当前加载的程序集的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获取当前的“索引”(counter?)?我想用它在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> 

回答

8

是啊 - 你只需要使用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,但它更可能以这种方式工作 - 希望你可以制定出翻译:)

+0

是它也可以用“正常”(SQL-等)LINQ查询? 例如... '的XDocument XML =新的XDocument(新的XElement( “项目”, 从项目中someItemsResourses 其中item.FullName.length => 5 oderby项目降 选择新的XElement( “项目”, new XAttribute(“id”,?how?),item.FullName)))' –

+0

@ V-Light:是的,但是将查询表达式嵌入到其他语句中对我来说总是很古怪。 –

+0

是的,这听起来很理性,但无论如何,我怎么能在类似于SQL的LINQ查询中实现“counter”?只是想知道它的样子。对于这种情况,查询表达式必须嵌入到另一个语句:) –

0

@ V-灯,

你可以做这样的事情让你的迭代指数:

XDocument xml = new XDocument(New XElement("Items", from item in someItemsResourses where item.FullName.length => 5 orderby item descending //Get Iterator Index here and make use of it as you wish let currIndex = someItemsResourses.IndexOf(item) select new XElement("item", new XAttribute("id", ?how?), item.FullName))) 
相关问题