يمكنك استخدام LINQ أنواع و طرق الإرشاد في IronPython?

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

  •  06-07-2019
  •  | 
  •  

سؤال

هل من الممكن استخدام LINQ أنواع و طرق الإرشاد في IronPython?

إذا كان الأمر كذلك كيف ؟ و أيضا هناك في كثير من الأحيان أكثر 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__']
>>>

والذي يجمع عليه متماشية مع آيرن روبي 1.1 في طريقة using_clr_extensions.

نصائح أخرى

بعض الأشياء التي كنت تفعل مع LINQ يمكن القيام به مع قائمة comprehensions:

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

أو يمكنك استخدام خريطة, الحد, و التصفية:

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

ولكن قائمة comprehensions هي أكثر من ذلك بكثير "Pythonic" من استخدام البرمجة الوظيفية بنيات.للحد من الأشياء النظر في استخدام "".الانضمام أو مجموع.و يمكنك التحقق من القيمة الحقيقة كاملة iterables باستخدام أي و كل

فقط تذكر هذه الترجمة:

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 قدم في البداية هذه الميزة، ولكن كان هناك <لأ href = "HTTP: قضية //ironpython.codeplex.com/workitem/30379">an حيث توقفت من كونها صالحة للاستعمال حقا.

أنا <لأ href = "http://jeroen.haegebaert.com/post/2010/07/24/Chained-method-syntax-in-IronPython-(alternative-to-extension-methods)" يختلط = " نوفولو noreferrer "> صفت C # فئة مجمع حول طرق الإرشاد LINQ إلى تحقيق جملة مماثلة لC # الصورة" جملة بالسلاسل طريقة تمديد "في و IronPython.

والفكرة هي أن يكون هناك نوع من الدرجة الديكور حول 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