I'm writing a simpl开发者_StackOverflow中文版e encrypting for my homework. I have completed it, now i'm trying to improve my code with lambda expressions. Object in list doesn't change after lambda expression. Is it using a local variable ? And how can i do that with lambda expression. I wrote my code following
public override string Encrypt(string code)
{
List<Byte> encodedBytes = new List<Byte>(ASCIIEncoding.ASCII.GetBytes(code));
encodedBytes.ForEach(o => { if (hash.Contains(o))
o = hash.ElementAt((hash.IndexOf(o) + ShiftAmount) % hash.Count); });
return ASCIIEncoding.ASCII.GetString(encodedBytes.ToArray());
}
I'm waiting for your answer, thanks...
It is indeed using a local variable. If you want the return value of the lambda to assign back into the list, use ConvertAll instead of ForEach.
If you want a more problem related solution this will be more suitable
public static class Extensions
{
public static void ModifyWhere<T>(this List<T> list, Func<T, bool> condition, Func<T, T> act)
{
for (int i = 0; i < list.Count; i++)
{
if (condition(list[i]))
list[i] = act(list[i]);
}
}
}
and this solution won't be specific, method taking a bool returning function as a condition, and returning function as an action.
a sample usage will be following
mylist.ModifyWhere(someBoolReturningFunction, someTReturningFunction);
Yes, in your code the variable 'o' is a local variable in the scope of the anonymous method passed to the ForEach method. Changes to it will not be reflected outside that scope.
You could write your own extension method to iterate over your list, modifying the items and then returning a new list based on your lambda like this:
public static class Extensions
{
public static List<T> ModifyEach<T>(this List<T> list, Func<T, T> method)
{
List<T> mod = new List<T>();
foreach (T e in list)
{
mod.Add(method(e));
}
return mod;
}
}
Sample usage:
List<string> f = new List<string>()
{
"hello",
"world"
};
f = f.ModifyEach(x => x.ToUpper());
f.ForEach(x => Console.WriteLine(x));
精彩评论