We know that "Action, Func, and Predicate are predefined universal delegates, so as a delegate, they can point to functions with the specified signature."
I have the following data access scenario in which Func<T,R> helps in avoiding a foreach loop in the calling method. Approach 2 has no cycles. Here Func<T,R> helped to avoid the loop.
What are the other scenarios for generic delegates in which it can save many lines of code?
LITERATURE
THE CODE
Approach 1
public class MyCommonDAL { public static IEnumerable<IDataRecord> ExecuteQueryWithTextCommandType(string commandText, List<SqlParameter> commandParameters) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandType = CommandType.Text; command.CommandText = commandText; command.CommandTimeout = 0; command.Parameters.AddRange(commandParameters.ToArray()); connection.Open(); using (var rdr = command.ExecuteReader()) { while (rdr.Read()) { yield return rdr; } rdr.Close(); } } } } } public class MyLogDAL { public List<LogSeverityType> GetLogSeveritiesFirstApproach(LogSeverityType logSeverityType) { List<SqlParameter> commandParameters = new List<SqlParameter>() { new SqlParameter {ParameterName = "@CreatedDateTime", Value = logSeverityType.CreatedDateTime, SqlDbType = SqlDbType.DateTime} }; string commandText = @"SELECT * FROM dbo.LogSeverityType WHERE CreatedDateTime > @CreatedDateTime"; var results = MyCommonDAL.ExecuteQueryWithTextCommandType(commandText, commandParameters); List<LogSeverityType> logSeverities = new List<LogSeverityType>();
Approach 2
public class MyCommonDAL { public static IEnumerable<T> ExecuteQueryGenericApproach<T>(string commandText, List<SqlParameter> commandParameters, Func<IDataRecord, T> factoryMethod) {
Different code required
public class LogSeverityType { public int LogSeverityTypeID { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime CreatedDateTime { get; set; } public static LogSeverityType LogSeverityTypeFactory(IDataRecord record) { return new LogSeverityType { LogSeverityTypeID = (int)record[0], Name = (string) record[1], Description = (string)record[2], CreatedDateTime = (DateTime) record[3] }; } } static void Main(string[] args) { MyLogDAL logDAL = new MyLogDAL(); LogSeverityType logSeverityType = new LogSeverityType(); logSeverityType.CreatedDateTime = Convert.ToDateTime("1/1/2000"); List<LogSeverityType> logSeverities = logDAL.GetLogSeveritiesSecondApproach(logSeverityType); }
Lijo
source share