Hello Functional C# Friends,
So this time i am trying to compact my code and write in more functional , lambda style, as well as i would like to avaoid creating unneccessary lists and classes and let compiler do the work for me. I did manage to convert some small piece of code in functional way but after that i dont have much idea as how to go about.
var errorList = new List<DataRow>();
IEnumerable<DataRow> resultRows = GetResultRows();
resultRows
.Filter(row => row.Field<string>("status").Equals("FAILURE", StringComparison.InvariantCultureIgnoreCase))
.ForEach(row => { errorList.Add(row); });
if (errorList.Count > 0)
{
var excludedBooks = new List<string>();
foreach (DataRow row in errorList)
{
if (ToUseBooksList.Contains((string)row["main_book"]))
{
BookCheckResults.AddRow(string.Format("Error for MainBook {0}, RiskType {1}",
row["main_book"], row["risk_type"]));
if (!excludedBooks.Contains((string)row["main_book"]))
{
excludedBooks.Add((string)row["main_book"]);
}
}
}
}
My Extension methods :
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (action == null)
throw new ArgumentNullException("action");
foreach (var item in collection)
action(item);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> source, Predicate<T> func)
{
foreach (var item in source)
{
if (func(item))
yield return item;
}
}
I will highly appreciate if you can help me structing this code is more functional, lambda style.