简体   繁体   中英

Trying to transform delegate function to extension generics method with lambda

My intention is to... void Encrypt any property value in 'TSource', it could be all or some of properties depend on selector.

This is my former code:

   ...IEnumerable<TSource>().ForEach(delegate(TSource ts)
                                  { 
                                    ts.prop0 = ts.prop0.Encrypt();
                                    ts.prop1 = ts.prop1.Encrypt();
                                    Etc...
                                  });

IEnumerable Extension:

...ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
        {
            foreach (TSource item in source)
                action(item);
        }

string Extension:

...string Encrypt(this string strPlainText)
    {
        if (!string.IsNullOrEmpty(strPlainText))
            return SomeClass.Encrypt(strPlainText);
        return strPlainText;
    }

The point is how to transform all above into IEnumerable Extension just in line syntax,may or may not look like this:

    //Encrypt all props. in Tsource.
   ...IEnumerable<TSource>().EncryptProp();  

    //Encrypt any prop. in Tsource. with selector property 
   ...IEnumerable<TSource>().EncryptProp(ts => ts.prop0);  
   ...IEnumerable<TSource>().EncryptProp(ts => ts.prop0,ts.prop1);  
   ...IEnumerable<TSource>().EncryptProp(ts => ts.prop0,ts.prop1,Etc...);  

I'd be glad to take any suggestions.

It is hard to tell exactly how this could be done because you code sample is incomplete. However, from what I can understand, you have an IEnumerable<TSource> and you would like to perform the same operation for all of the properties for all of the items in this sequence?

This requires a couple of things, first look at SelectMany . This projects each element in the source to a new sequence, flattening them all into a single sequence.

The second thing is how to create an IEnumerable<TResult> from all of the properties of each element. This is not so easy! If your Prop0 , Prop1 could be stored as a dictionary that would help!

You could use reflection. Something like this:

IEnumerable<MyObject> source = ///your source
var allProperties = source.SelectMany(s =>
              typeof(MyType).GetProperties().Select(p => p.GetValue(s, null));

However, as strings are immutable, if you Encrypt the resulting sequence, your source MyObject instances will not reflect this change.

If you really want to do this, store your properties in a dictionary!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM