Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- List<int> numbers = new List<int> { 1, 5, 6, 3, 8, 7, 9, 2, 3, 4, 5, 6, };
- // To get the count of those that are less than four we might write:
- int lessThanFourCount = numbers.Where(n => n < 4).Count();
- // But this can also be written as:
- Func<int, bool> lessThanFour = n => n < 4;
- int lessThanFourCount = numbers.Where(lessThanFour).Count();
- ...
- DoSomethingPotentiallyBad((x) => x * 2, 0); // both delegates do
- DoSomethingPotentiallyBad((x) => 2 / x, 0); // something different ...
- ...
- static int DoSomethingPotentiallyBad(Func<int, int> function, int input)
- {
- // ... but get exception handled all the same way
- try
- {
- return function.Invoke(input);
- }
- catch
- {
- Console.WriteLine("Evaluation failed! Return 0.");
- return 0;
- }
- }
- public static string ToDelimitedString<T>(
- this IEnumerable<T> source, Func<T, string> converter, string separator)
- {
- // error checking removed for readability
- StringBuilder sb = new StringBuilder();
- foreach (T item in source)
- {
- sb.Append(converter(item));
- sb.Append(separator);
- }
- return (sb.Length > 0) ?
- sb.ToString(0, sb.Length - separator.Length) : string.Empty;
- }
- // ...
- List<int> e1 = new List<int> { 1, 2, 3 };
- // convert to "2|4|6"
- string s1 = e1.ToDelimitedString(x => (x * 2).ToString(), "|");
- DateTime[] e2 = new DateTime[]
- { DateTime.Now.AddDays(-100), DateTime.Now, DateTime.Now.AddDays(100) };
- // convert to "Tuesday, Thursday, Saturday"
- string s2 = e2.ToDelimitedString(x => x.DayOfWeek.ToString(), ", ");
- List<MyCustomType> e3 = new List<MyCustomType>
- { new MyCustomType("x"), new MyCustomType("y"), new MyCustomType("z") };
- // convert to "X and Y and Z"
- string s3 = e3.ToDelimitedString(x => x.Name.ToUpper(), " and ");
Add Comment
Please, Sign In to add comment