Lambda in C # extension method

Suppose I want to write an extension method to upload some data from T[,] to CSV:

 public static void WriteCSVData<T>(this T[,] data, StreamWriter sw) { for (int row = 0; row < data.GetLength(0); row++) for (int col = 0; col < data.GetLength(1); col++) { string s = data[row, col].ToString(); if (s.Contains(",")) sw.Write("\"" + s + "\""); else sw.Write(s); if (col < data.GetLength(1) - 1) sw.Write(","); else sw.WriteLine(); } } 

which I could call with

 using (StreamWriter sw = new StreamWriter("data.csv")) myData.WriteCSVData(sw); 

but suppose myData is Complex[,] , and I want to write the value of a complex number, not the full value. It would be convenient if I could write:

 using (StreamWriter sw = new StreamWriter("data.csv")) myData.WriteCSVData(sw, d => d.Magnitude); 

but I'm not sure how to implement this in the extension method or if it is possible.

+5
source share
2 answers

You can write an overload of an existing method as follows:

 public static void WriteCSVData<T, TValue>(this T[,] data, StreamWriter sw, Func<T,TValue> func) { for (int row = 0; row < data.GetLength(0); row++) for (int col = 0; col < data.GetLength(1); col++) { string s = func(data[row, col]).ToString(); if (s.Contains(",")) sw.Write("\"" + s + "\""); else sw.Write(s); if (col < data.GetLength(1) - 1) sw.Write(","); else sw.WriteLine(); } } 

and use it the way you like:

 using (StreamWriter sw = new StreamWriter("data.csv")) myData.WriteCSVData(sw, d => d.Magnitude); 
+8
source

Define a delegate with parameter type T and enter a string type. Add a parameter to the WriteCSVData method with the delegate type.

 delegate string ExtractValueDelegate<T>(T obj); public static void WriteCSVData<T>(this T[,] data,ExtractValueDelegte<T> extractor , StreamWriter sw) { ... } // calling the method myData.WriteCSVData(sw, d => d.Magnitude.ToString()); 
+1
source

Source: https://habr.com/ru/post/1202571/


All Articles