Quick Notes for easy understanding. Chapters are on C#.Net,Linq,OOPS,Design Patterns,UML,Tools for development, Databases and many others. - Sid
Tuesday, February 5, 2013
Function Techniques in C# : Currying
Named after Mathematician Haskell Curry.
Although it really was Schonfinkel who came up with the idea.
Syntax
Func<T1,TResult>
Func<int,int>
Example:1
void Main()
{
Func<string,string,int> str = (x,y)=>x.Length + y.Length ;
str("google","plus");
}
Example:2
static int Calculate(Func<int, int, int> op, int a, int b)
{
return op(a, b);
}
static void Main(string[] args)
{
int three = Calculate((x, y) => x + y, 1, 2);
int eight = Calculate((l, r) => l * r, 2, 4);
}
Example:3
DataTable newDataTable = new DataTable("filteredTable");
Func<DataTable, String[], DataRow, DataRow> NewRow = delegate(DataTable targetTable, String[] columns, DataRow srcRow)
{
if (targetTable == null)
throw new ArgumentNullException("targetTable");
if (columns == null)
throw new ArgumentNullException("columns");
if (srcRow == null) throw new ArgumentNullException("srcRow");
if (columns.Count() == 0) throw new ArgumentNullException("srcRow");
DataRow row = targetTable.NewRow();
foreach (var column in columns)
{
if (!targetTable.Columns.Contains(column))
targetTable.Columns.Add(column);
row[column] = srcRow[column];
}
return row;
};
var query = (from d in _MyDataset.Tables["Records"].AsEnumerable()
where d.Field<String>("Name").Equals("searchText", StringComparison.CurrentCultureIgnoreCase)
select NewRow(newDataTable, new[] { "Value" }, d));
if (query.Count() != 0) { DataTable result = query.CopyToDataTable(); }
Subscribe to:
Post Comments (Atom)
Code Formater
Paste Here Your Source Code | ||||||||||||||
Source Code Formatting Options | ||||||||||||||
|
||||||||||||||
Copy Formatted Source Code | ||||||||||||||
Preview Of Formatted Code |
ReplyDeleteExamples
The following example demonstrates how to declare and use a Func delegate. This example declares a Func variable and assigns it a lambda expression that converts the characters in a string to uppercase. The delegate that encapsulates this method is subsequently passed to the Enumerable.Select method to change the strings in an array of strings to uppercase.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
static class Func
{
static void Main(string[] args)
{
// Declare a Func variable and assign a lambda expression to the
// variable. The method takes a string and converts it to uppercase.
Func selector = str => str.ToUpper();
// Create an array of strings.
string[] words = { "orange", "apple", "Article", "elephant" };
// Query the array and select strings according to the selector method.
IEnumerable aWords = words.Select(selector);
// Output the results to the console.
foreach (String word in aWords)
Console.WriteLine(word);
}
}
/*
This code example produces the following output:
ORANGE
APPLE
ARTICLE
ELEPHANT
*/