Get the current enumerator (iterator?) In the LINQ query. Like the current index for loops

Is it possible to get the current Enumerator (... or an iterator? I don't know which tern is correct) in a LINQ query?

For example, I'm trying to generate XML output (via LINQ to XML) of all currently loaded assemblies.

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)))) 

The result looks like this:

 <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> 

Is there any way to get the current β€œindex” (counter?) From LINQ Selects? I would like to use it in 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> 
+6
source share
2 answers

Yup - you just need to use the Select overload, which takes Func<TSource, int, TResult> . So in C # it will be something like:

 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)))); 

Sorry, it’s not in VB, but it will work this way more likely - I hope you can develop a translation :)

+8
source

@ V-Light,

You can do something like this to get your iterator index:

 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))) 
0
source

Source: https://habr.com/ru/post/897705/


All Articles