Reputation: 35
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.
Upvotes: 0
Views: 164
Reputation: 70160
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!
Upvotes: 1