2017-07-06 93 views
3

我有一个关于IronPython中的使用方法的问题。假设我有一些集合,然后从该集合创建IronPython匿名类型,并且我想遍历该集合。我的代码如下所示:IronPython中的LINQ

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 

此代码正常工作。但是当我使用索引合并的Select方法时,我得到错误:'int'对象不可迭代。 Error

我的代码如下所示:

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 

谁能为我提供一些帮助?为什么第二种情况有错误?

PS:对于接口的使用我看了看这里:Interface In IronPython.对于匿名类型的使用我看了看这里:Anonymous objects in Python.

回答

0

我不能重现你直接的例子,我很好奇您使用的是创建列表的模块和了IEnumerable(我面对非泛型类型问题上MakeGenericType),但是,我设法重现您的问题在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) 

这引发了同样的错误

'int' object is not iterable.

因为拉姆达服用2个参数,所以我们只需要列举listInt给予适当的元组的拉姆达:

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) 

我希望它可以帮助你的系统类型,我喜欢的Python :-p

+1

嗨@PRMoureu,感谢您的帮助,将尝试此解决方案,谢谢!对不起提及我使用的模块。为了能够访问.NET类型,我只导入了clr和System,然后添加了对System.Core.dll的引用。要访问List 类,我使用了System.Cllections.Generic命名空间。为了使用Enumerable扩展,我从System.Linq命名空间导入了扩展。此代码的伪代码如下所示:从System.Collections.Generic import *导入系统,clr.AddReference('System.Core'),clr.ImportExtensions(System.Linq),从System.Linq导入* – Bill