01/04
.Net Framework 3.5 Features
- Func<T,TResult>: an encapsulation method with T input and Tresult output
- eg. Func<string, string> selector = str => str.ToUpper();
string[] words = { "orange", "apple", "Article", "elephant" };
IEnumerable<String> aWords = words.Select(selector); - Action<T> : no output
- Anonymous Type : var
- Extension Method
- Property :
- public int NumberOfCars { get; set; }
- Partial Methods ; Object Initialize Syntax
- Point finalPoint = new Point { X = 30, Y = 30 };
Linq Sample Code with Func<T>
….
string[] currentVideoGames = {"Morrowind", "BioShock",
"Half Life 2: Episode 1", "The Darkness",
"Daxter", "System Shock 2"};
//1.Linq Expression can var
IEnumerable<string> subset = from game in currentVideoGames
where game.Length > 6
orderby game
select game;
//2.Lambda Expression can use var
Func<string, string> newVariable = game => game;
IEnumerable<string> subset2 = currentVideoGames.Where(game => game.Length > 6).OrderBy(game => game).Select(newVariable);
//3. Enumerable
var subset3 = Enumerable.Where(currentVideoGames, game => game.Length > 6).OrderBy(game => game).Select(game => game);
//4. With Func
//Func<string, bool> searchfilter = delegate(string game)
// {
// return game.Length > 6;
// };
Func<string, bool> searchfilter2 = game => game.Length > 6;
var subset4 = currentVideoGames.Where(searchfilter2).OrderBy(game => game).Select(game => game);
// Using oftype<T>
// Extract the ints from the ArrayList.
ArrayList myStuff = new ArrayList();
myStuff.AddRange(new object[] { 10, 400, 8, false, new Object(), "string data" });
IEnumerable<int> myInts = myStuff.OfType<int>();
// Prints out 10, 400, and 8.
foreach (int i in myInts)
{
Console.WriteLine("Int value: {0}", i);
}
// 封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
Func<string, string> convertMeth = delegate(string s)
{
return s.ToUpper();
};
// Linq Differnce
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
var carDiff = (from c in myCars select c)
.Except(from c2 in yourCars select c2);
Console.WriteLine("Here is what you don't have, but I do:");
foreach (string s in carDiff)
Console.WriteLine(s); // Prints Yugo.
….
0 Comments:
Post a Comment
<< Home