ThreadClass
using System;
using System.Threading;
using System.Linq;
using System.Collections.Generic;
namespace ThreadingTester
{
/*“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。 所有 Lambda 表达式都使用 Lambda 运算符 =>,该运算符读为“goes to”。该 Lambda 运算符的左边是输入参数(如果有),右边包含表达式或语句块。
=> 标记称作 lambda 运算符。该标记在 lambda 表达式中用来将左侧的输入变量与右侧的 lambda 体分离。Lambda 表达式是与匿名方法类似的内联表达式,但更加灵活;在以方法语法表示的 LINQ 查询中广泛使用了 Lambda 表达式。
*/
// Declare a delegate
delegate void Printer(string s);
delegate int del(int i);
class TestClass
{
static void Main33()
{
//(x, y) => x == y ;
//(input parameters) => {statement;}
//Lambda 语句与 Lambda 表达式类似,只是语句括在大括号中,Lambda 语句的主体可以包含任意数量的语句;但是,实际上通常不会多于两个或三个语句。
//delegate void TestDelegate(string s);
//…
//TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
//myDel("Hello");
//----------------------------------------------------------
//----------------------------------------------------------
del myDelegate = x => x * x;
int jF = myDelegate(5); //j = 25
string[] words = { "cherry", "apple", "blueberry" };
int shortestWord = words.Min(w2 => w2.Length);
Console.WriteLine(shortestWord.ToString());
//可以显式指定输入变量的类型或让编译器进行推断;在任一情况下,此变量在编译时都是强类型的。当指定类型时,必须用括号将类型名称和变量名括起,如以下示例所示:
int shortestWord2 = words.Min((string w) => w.Length);
//下面的示例演示如何使用两个输入变量为标准查询运算符 Enumerable.Where 编写 lambda 表达式。此表达式将返回其长度小于其在数组中的索引位置的所有字符串。
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index55) => digit.Length < index55);
// Instatiate the delegate type using an anonymous method:
Printer p = delegate(string j)
{
System.Console.WriteLine(j);
};
// Results from the anonymous delegate call:
p("The delegate using the anonymous method is called.");
// The delegate instantiation using a named method "DoWork":
p = new Printer(TestClass.DoWork);
// Results from the old style delegate call:
p("The delegate using the named method is called.");
}
// The method associated with the named delegate:
static void DoWork(string k)
{
System.Console.WriteLine(k);
}
}
/* Output:
The delegate using the anonymous method is called.
The delegate using the named method is called.
*/
class ThreadClass
{
public static ManualResetEvent mre = new ManualResetEvent(false);
public static void trmain()
{
Thread tr = Thread.CurrentThread;
Console.WriteLine("thread: waiting for an event");
mre.WaitOne();
Console.WriteLine("thread: got an event");
for (int x = 0; x < 10; x++)
{
Thread.Sleep(3000);
Console.WriteLine(tr.Name + ": " + x);
}
}
static void Main55(string[] args)
{
//匿名方法的参数的范围是“匿名方法块”。
System.Threading.Thread t1 = new System.Threading.Thread(delegate()
{
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
Thread thrd1 = new Thread(new ThreadStart(trmain));
thrd1.Name = "thread1";
thrd1.Start();
for (int x = 0; x < 10; x++)
{
Thread.Sleep(900);
Console.WriteLine("Main:" + x);
if (x == 5)
{
mre.Set();
}
}
while (thrd1.IsAlive)
{
Thread.Sleep(100);
Console.WriteLine("Main: waiting for thread to stop");
}
}
}
//-----------------------------------
public class DelegateExample
{
delegate string ConvertMethod(string inString);
public static void Main1()
{
string name = "Dakota";
// Instantiate delegate to reference UppercaseString method
ConvertMethod convertMeth = UppercaseString;//第1种方法
Console.WriteLine(convertMeth(name));
ConvertMethod dd = new ConvertMethod(UppercaseString);//第2种方法
Console.WriteLine(dd(name));
// Use delegate instance to call UppercaseString method
//Console.WriteLine(convertMeth(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
//以下示例简化了此代码,它所用的方法是实例化 Func<T, TResult> 委托,而不是显式定义一个新委托并将命名方法分配给该委托。
public class GenericFunc
{
public static void Main2()
{
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
//也可以在 C# 中将 Func<T, TResult> 委托与匿名方法一起使用。
public class Anonymous
{
public static void Main3()
{
Func<string, string> convert = delegate(string s) { return s.ToUpper(); };
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
//您也可以按照以下示例所演示的那样将 lambda 表达式分配给 Func<T, TResult> 委托
public class LambdaExpression
{
public static void Main4()
{
Func<string, string> convert = s => s.ToUpper();
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
//下面的示例演示如何声明和使用 Func<T, TResult> 委托。此示例声明一个 Func<T, TResult> 变量,并为其分配了一个将字符串中的字符转换为大写的 lambda 表达式。随后将封装此方法的委托传递给 Select 方法,以将字符串数组中的字符串更改为大写。
static class Func
{
static void Main66(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<string, string> 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<String> aWords = words.Select(selector);
// Output the results to the console.
foreach (String word in aWords)
{
Console.WriteLine(word);
}
//--------------------Select 将序列中的每个元素投影到新表中。 selector 类型:System.Func<TSource, TResult>, 应用于每个元素的转换函数。
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
foreach (int num in squares)
{
Console.WriteLine(num);
}
/*
This code produces the following output:
1
4
9
16
25
36
49
64
81
100
*/
//-----------------------------------------------------
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
var firstSmallNumbers = numbers.TakeWhile((n, index3) => n >= index3);
}
}
//-----------------------------------------
delegate bool D();
delegate bool D2(int i);
class Test
{
D del;
D2 del2;
//Lambda 可以引用“外部变量”,这些变量位于在其中定义 Lambda 的封闭方法或类型的范围内。将会存储通过这种方法捕获的变量以供在 Lambda 表达式中使用,即使变量将以其他方式超出范围或被作为垃圾回收。必须明确地分配外部变量,然后才能在 Lambda 表达式中使用该变量。
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del = () => { j = 10; return j > input; };
// del2 will be invoked after TestMethod goes out of scope.
del2 = (x) => { return x == j; };
// Demonstrate value of j:
// Output: j = 0
// The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j);
// Invoke the delegate.
bool boolResult = del();
// Output: j = 10 b = True
Console.WriteLine("j = {0}. b = {1}", j, boolResult);
}
static void Main44()
{
Test test = new Test();
test.TestMethod(5);
// Prove that del2 still has a copy of local variable j from TestMethod.
bool result = test.del2(10);
// Output: True
Console.WriteLine(result);
}
}
//-------------------------------------
public class Product
{
public int ProductID
{
get;
set;
}
public int CategoryID
{
get;
set;
}
public bool Discontinued
{
get;
set;
}
public int SupplierID
{
get;
set;
}
public int UnitPrice
{
get;
set;
}
public string StringTest
{
get;
set;
}
public int UnitsInStock
{
get;
set;
}
public int ReorderLevel
{
get;
set;
}
}
public class Order
{
public DateTime OrderDate
{
get;
set;
}
public DateTime ShippedDate
{
get;
set;
}
public int ShippedID
{
get;
set;
}
}
public class Employee
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string HomePhone
{
get;
set;
}
public string Country
{
get;
set;
}
public DateTime HireDate
{
get;
set;
}
}
class Program
{
static void Main22(string[] args)
{
var arr = new[] { 8, 5, 89, 3, 56, 4, 1, 58 };
//var userlist = new[] { "a", "b", "c" };
var m = from n in arr where n < 5 orderby n select n;
foreach (var n in m)
{
Console.WriteLine(n);
}
Console.ReadLine();
}
static void Main66(string[] args)
{
string[] languages = { "Java", "C#", "C++", "Delphi", "VB.net", "VC.net", "C++ Builder", "Kylix", "Perl", "Python" };
var query = from item11 in languages orderby item11 group item11 by item11.Length into lengthGroups orderby lengthGroups.Key descending select lengthGroups;
foreach (var item in query)
{
Console.WriteLine("strings of length {0}", item.Key);
foreach (var val in item)
{
Console.WriteLine(val);
}
}
//--------------------------------------------------------
List<Product> Products = new List<Product>();
Product model1 = new Product();
model1.CategoryID = 3;
model1.Discontinued = false;
model1.SupplierID = 6;
model1.UnitPrice = 466;
Product model2 = new Product();
model2.CategoryID = 743;
model2.Discontinued = false;
model2.SupplierID = 6;
model2.UnitPrice = 466;
Product model3 = new Product();
model3.CategoryID = 379;
model3.Discontinued = false;
model3.SupplierID = 64;
model3.UnitPrice = 65466;
Product model4 = new Product()
{
CategoryID = 8,
Discontinued = false,
SupplierID = 45,
UnitPrice = 74,
};
Products.Add(model1);
Products.Add(model2);
Products.Add(model3);
Products.Add(model4);
//var q = from p in Products group p by p.CategoryID into g select new { g.Key };//Linq使用Group By和Count得到每个CategoryID中产品的数量。说明:先按CategoryID归类,取出CategoryID值和各个分类产品的数量。
var categories = from p in Products group p by new { p.CategoryID } into g select new { g.Key, g };
foreach (var item in categories)
{
Console.WriteLine("strings of length {0}", item.Key);
foreach (Product val in item.g)
{
Console.WriteLine(val);
}
}
//-------------------------------
var q33ds = from p in Products
select new
{
fdsf = p.CategoryID,
gdsfgdsf = p.SupplierID / 2,
Availability = p.UnitPrice - p.UnitPrice < 0 ? "Out Of Stock" : "In Stock"
};//此外在所得的序列中将CategoryID字段重命名为fdsf,设置为SupplierID除以2
var q3366 = from p in Products
select new
{
p.UnitPrice,
fdsf = new
{
p.SupplierID,
p.Discontinued
},
};//其select操作使用了匿名对象,而这个匿名对象中,其属性也是个匿名对象。
var q336655 = from p in Products
select new
{
p.UnitPrice,
fdsf = from p1 in Products where p1.CategoryID > 0 select p1,
fds = fds(p.CategoryID) //调用本地方法
};//返回的对象集中的每个对象fdsf属性中,又包含一个集合。也就是每个对象也是一个集合类。
var q33665555 = (from p in Products select p).Distinct();//Distinct用于查询不重复的结果集。
//---------------------------------------------------------------------------------------------------
var q33 = from p in Products group p by p.CategoryID into g select new { g.Key, NumProducts = g.Count(p => p.Discontinued) };//Linq使用Group By和Count得到每个CategoryID断货产品的数量。Count函数里,使用了Lambda表达式,Lambda表达式中的p,代表这个组里的一个元素或对象,即某一个产品。
//-------------------------------
var q2 = from p in Products group p by p.CategoryID into g where g.Count() >= 10 select new { g.Key, ProductCount = g.Count() };//根据产品的―ID分组,查询产品数量大于10的ID和产品数量。
//-------------------------------
var categories4 = from p in Products group p by new { p.CategoryID, p.SupplierID } into g select new { g.Key, g };//Linq使用Group By按CategoryID和SupplierID将产品分组。既按产品的分类,又按供应商分类。在by后面,new出来一个匿名类。这里,Key其实质是一个类的对象,Key包含两个Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍历CategoryID的值。
//-------------------------------
var categories22 = from p in Products group p by new { Criterion = p.UnitPrice > 10 } into g select g;//表达式(Expression) 使用Group By返回两个产品序列。第一个序列包含单价大于10的产品。第二个序列包含单价小于或等于10的产品。说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。
//其中的 into 关键字表示 将前一个查询的结果视为后续查询的生成器,这里是跟 group by 一起使用的。LINQ中的Group by不要跟 SQL 中的Group by 混淆,SQL 由于是二维结构,Group by 的一些逻辑受二维结构的约束,无法像 LINQ 中的Group by 这么灵活。
//----------------------------------------------
string c = "d";
var d = new { c };//编译器会创建一个叫做匿名类带有叫c的property。
var data = new { username = "zhuye", age = 26, Name = "rre" };
Console.WriteLine("username:{0} age:{1}", data.username, data.age);//匿名类型允许开发人员定义行内类型,无须显式定义类型。常和var配合使用,var用于声明匿名类型。定义一个临时的匿名类型在LINQ查询句法中非常常见,我们可以很方便的实现对象的转换和投影。
}
protected static int fds(int k)
{
return 0;
}
}
public static class helper
{
//很多时候我们需要对CLR类型进行一些操作,苦于无法扩展CLR类型的方法,只能创建一些helper方法,或者生成子类。扩展方法使得这些需求得以实现,同时也是实现LINQ的基础。定义扩展方法需要注意,只能在静态类中定义并且是静态方法,如果扩展方法名和原有方法名发生冲突,那么扩展方法将失效。
public static string MD5Hash(this string s)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5");
}
public static bool In(this object o, IEnumerable<string> b)
{
foreach (object obj in b)
{
if (obj == o)
return true;
}
return false;
}
}
public static class helper444
{
public static void dddd()
{
// 调用扩展方法
Console.WriteLine("123456".MD5Hash());
Console.WriteLine("1".In(new[] { "1", "2", "3" }));
}
}
//--------------------------
public class Person
{
public string username { get; set; }
public int age { get; set; }
public override string ToString()
{
return string.Format("username:{0} age:{1}", this.username, this.age);
}
}
public class Person22
{
public static void dddd()
{
Person p = new Person() { username = "zhuye", age = 26 };
Console.WriteLine(p.ToString());
//----------------------------
var persons = new List<Person>
{
new Person {username = "a", age=1},
new Person {username = "b", age=2}
};
foreach (var p1 in persons)
{
Console.WriteLine(p1.ToString());
}
//----------------------------Lambda表达式
var list = new[] { "aa", "bb", "ac" };
var result = Array.FindAll(list, s => s.IndexOf("a") > -1);
foreach (var v in result)
{
Console.WriteLine(v);
}
//---------------------------------
persons = new List<Person>
{
new Person {username = "a", age=19},
new Person {username = "b", age=20},
new Person {username = "a", age=21},
};
var selectperson = from p11 in persons where p.age >= 20 select p.username.ToUpper();//LINQ查询句法可以实现90%以上T-SQL的功能(由于T-SQL是基于二维表的,所以LINQ的查询语法会比T-SQL更简单和灵活),
//上面的查询句法等价于下面的代码:
var selectperson11 = persons.Where(p11 => p11.age >= 20).Select(p22 => p22.username.ToUpper());
foreach (var p11 in selectperson)
{
Console.WriteLine(p11);
}
}
}
//-----------------------------------------
}
posted on 2011-11-15 22:35 breakpoint 阅读(219) 评论(0) 编辑 收藏 举报