LINQ in IronPython
I have a question about a usage method in IronPython. Let's say I have a collection of some sort and then I create an anonymous IronPython type from that collection and I want to iterate over this entire collection. My code looks like this:
listInt = List[int]([0, 1, 2, 3, 4])
firstCollection = listInt.Select(lambda(v): type('SomeType', (object,),{"TypeValue": v*v, "TypeIndex": v})())
enumeratorFirst = IEnumerable[object].GetEnumerator(firstCollection)
while enumeratorFirst.MoveNext():
item = enumeratorFirst.Current
This code works fine. But when I use the Select method with index included, I get the error: the "int" object is not iterable.
My code looks like this:
listInt = List[int]([0, 1, 2, 3, 4])
secondCollection = listInt.Select(lambda(v, i): type('SomeType', (object,), {"TypeValue": v*v, "TypeIndex": i})())
enumeratorSecond = IEnumerable[object].GetEnumerator(secondCollection)
while enumeratorSecond.MoveNext():
item = enumeratorSecond.Current
Can anyone help me? Why does the second case get an error?
PS: For using the interface, I looked here: Interface in IronPython. For using anonymous type, I looked here: Anonymous Objects in Python.
source to share
I cannot reproduce your direct example, I am curious which module you are using to create lists and IEnumerable (I ran into MakeGenericType on a non-standard type problem), HOWEVER, I was able to reproduce your problem in Python:
listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
{"TypeValue": v*v, "TypeIndex": i})(), listInt)
for item in secondCollection:
print(item)
This throws the same error
An object'int' is not iterable.
because the lambda takes 2 parameters, so we only need to enumerate listInt
to give the appropriate set for the lambda:
listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
{"TypeValue": v*v, "TypeIndex": i})(), enumerate(listInt))
for item in secondCollection:
print(item.TypeIndex, item.TypeValue)
>>> (0, 0)
>>> (1, 1)
>>> (2, 4)
>>> (3, 9)
>>> (4, 16)
Hope it helps you on System types, I prefer Python: -p
source to share