Ironpython에서 LINQ 유형 및 확장 방법을 사용할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/628482

  •  06-07-2019
  •  | 
  •  

문제

Ironpython에서 LINQ 유형 및 확장 방법을 사용할 수 있습니까?

그렇다면 어떻게? 또한 똑같은 일을하기 위해 종종 더 많은 Pythonic이 있습니까?

도움이 되었습니까?

해결책

Ironpython 2.7 마침내이 간격을 연결합니다 clr.ImportExtensions 네임 스페이스에서 대상 유형으로 확장 메소드를 추가하는 메소드

>& 'C:\Program Files\IronPython 2.7\ipy.exe'
IronPython 2.7 (2.7.0.40) on .NET 4.0.30319.225
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> clr.AddReference("System.Core")
>>> from System.Collections.Generic import List
>>> dir (List)
['Add', 'AddRange', 'AsReadOnly', 'BinarySearch', 'Capacity', 'Clear', 'Contains', 'ConvertAll', 'CopyTo', 'Count', 'Enu
merator', 'Equals', 'Exists', 'Find', 'FindAll', 'FindIndex', 'FindLast', 'FindLastIndex', 'ForEach', 'GetEnumerator', '
GetHashCode', 'GetRange', 'GetType', 'IndexOf', 'Insert', 'InsertRange', 'IsReadOnly', 'IsSynchronized', 'Item', 'LastIn
dexOf', 'MemberwiseClone', 'ReferenceEquals', 'Remove', 'RemoveAll', 'RemoveAt', 'RemoveRange', 'Reverse', 'Sort', 'Sync
Root', 'ToArray', 'ToString', 'TrimExcess', 'TrueForAll', '__add__', '__class__', '__contains__', '__delattr__', '__doc_
_', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce
__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__']
>>> import System
>>> clr.ImportExtensions(System.Linq)
>>> dir (List)
['Add', 'AddRange', 'Aggregate', 'All', 'Any', 'AsEnumerable', 'AsParallel', 'AsQueryable', 'AsReadOnly', 'Average', 'Bi
narySearch', 'Capacity', 'Cast', 'Clear', 'Concat', 'Contains', 'ConvertAll', 'CopyTo', 'Count', 'DefaultIfEmpty', 'Dist
inct', 'ElementAt', 'ElementAtOrDefault', 'Enumerator', 'Equals', 'Except', 'Exists', 'Find', 'FindAll', 'FindIndex', 'F
indLast', 'FindLastIndex', 'First', 'FirstOrDefault', 'ForEach', 'GetEnumerator', 'GetHashCode', 'GetRange', 'GetType',
'GroupBy', 'GroupJoin', 'IndexOf', 'Insert', 'InsertRange', 'Intersect', 'IsReadOnly', 'IsSynchronized', 'Item', 'Join',
 'Last', 'LastIndexOf', 'LastOrDefault', 'LongCount', 'Max', 'MemberwiseClone', 'Min', 'OfType', 'OrderBy', 'OrderByDesc
ending', 'ReferenceEquals', 'Remove', 'RemoveAll', 'RemoveAt', 'RemoveRange', 'Reverse', 'Select', 'SelectMany', 'Sequen
ceEqual', 'Single', 'SingleOrDefault', 'Skip', 'SkipWhile', 'Sort', 'Sum', 'SyncRoot', 'Take', 'TakeWhile', 'ToArray', '
ToDictionary', 'ToList', 'ToLookup', 'ToString', 'TrimExcess', 'TrueForAll', 'Union', 'Where', 'Zip', '__add__', '__clas
s__', '__contains__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__',
 '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__'
, '__str__', '__subclasshook__']
>>>

Ironruby 1.1과 일치합니다 using_clr_extensions 방법.

다른 팁

LINQ로 수행 한 작업 중 일부는 목록 이해력으로 수행 할 수 있습니다.

[myFunc(i) for i in numbers if i > 3]

또는지도, 축소 및 필터를 사용할 수 있습니다.

map(myFunc, filter(lambda x: x > 3, numbers))

그러나 목록 이해력은 기능적 프로그래밍 구성을 사용하는 것보다 훨씬 "pythonic"입니다. 물건을 줄이려면 사용을 고려하십시오 "".가입하다 또는 합집합. 그리고 당신은 사용하여 전체 반복의 진실 값을 확인할 수 있습니다. 어느 그리고 모두

이 번역을 기억하십시오.

Select -> map
Where -> filter
Aggregate -> reduce

그리고 당신은 당신의 길에 잘 될 것입니다!

~ 안에 Ironpython 2.7.1 당신은 가지고 있습니다 clr.importextensions 이 유스 케이스의 경우.

import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)

# will print 3 and 4 :)
[2, 3, 4].Where(lambda x: x != 2).ToList().ForEach(System.Console.WriteLine)

약간의 배경 : Ironpython 2.7 처음 에이 기능을 소개했지만 그랬습니다 이슈 그것은 정말로 그것을 사용하지 못하게 막았습니다.

C# 래퍼 클래스를 설명했습니다 IronpyThon에서 C#'S'Chained Extension Method '구문과 유사한 구문을 달성하기위한 LINQ 확장 방법 주변.

아이디어는 주변에 일종의 데코레이터 클래스를 갖는 것입니다. IEnumerable 그것은 단순히 확장 방법을 부릅니다. 아마도이 래퍼 클래스는 Ironpython에서도 잘 쓰여질 수 있지만, 나는 아직 파이썬에 유창하지 않습니다 :-)

public class ToLinq<T> : IEnumerable<T>
{
    private readonly IEnumerable<T> _wrapped;

    public ToLinq(IEnumerable<T> wrapped)
    {
       _wrapped = wrapped;
    }

    public ToLinq<T> Where(Func<T, bool> predicate)
    {
        return new ToLinq<T>(_wrapped.Where(predicate));
    }


    // ... similar methods for other operators like Select, Count, Any, ...

}

이것은 이와 유사한 구문을 허용합니다.

johns = ToLinq[Customer](customers)\
          .Where(lambda c: c.Name.StartsWith("John"))\
          .Select(lambda c: c.Name)

면책 조항 : 이것은 내가 학습 운동으로 시도한 것입니다. 저는 실제 프로젝트에서 이것을 사용하지 않았습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top