在IronPython中使用LINQ

3
我有一个问题是关于IronPython的用法。假设我有一些集合,然后我从该集合创建了一个IronPython匿名类型,并且我想迭代整个集合。我的代码如下:
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' object is not iterable”。 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

有人能帮我解决问题吗?为什么第二种情况出错了?

P.S.: 我查看了这里的接口用法:IronPython中的接口。 对于匿名类型的使用,我查看了这里:Python中的匿名对象。

1个回答

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'对象不可迭代。

因为lambda函数接受两个参数,所以我们只需要枚举listInt来给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)

希望这可以帮助你了解系统类型,我更喜欢Python :-p


1
嗨@PRMoureu,感谢您的帮助,我会尝试这个解决方案,谢谢!很抱歉没有提到我使用的模块。为了访问.NET类型,我只是导入了clr和System,然后添加了对System.Core.dll的引用。为了访问List<T>类,我使用了System.Cllections.Generic命名空间。为了使用Enumerable扩展,我从System.Linq命名空间导入了扩展。这个伪代码看起来像这样:import clr,import System,clr.AddReference('System.Core'),clr.ImportExtensions(System.Linq),from System.Collections.Generic import *,from System.Linq import *。 - Bill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接