点滴杂记

来源:互联网 发布:distinct unique sql 编辑:程序博客网 时间:2024/06/11 11:31
Random rd = new Random(Guid.NewGuid().GetHashCode());//----------------------------------------------------------------------------------------------------------------------------------------------正则平衡组,匹配相等的{ 和 }\{((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}正则平衡组,匹配相等的{"title":"和 }\{"title":"((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}Dim reg = Regex.Matches(x, "\{""title"":""((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}")TextBox1.Text = reg.Item(0).ToString()//----------------------------------------------------------------------------------------------------------------------------------------------//C# 的高效方法取得图片的像素区数据Bitmap image = (Bitmap)pictureBox1.Image;// Lock the bitmap's bits.    Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);  BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);  // Get the address of the first line.  IntPtr ptr = bmpData.Scan0;  // Declare an array to hold the bytes of the bitmap.  int bytes = Math.Abs(bmpData.Stride) * image.Height;  byte[] rgbValues = new byte[bytes];  // Copy the RGB values into the array.  Marshal.Copy(ptr, rgbValues, 0, bytes);  // Unlock the bits.  image.UnlockBits(bmpData);  return rgbValues;  //----------------------------------------------------------------------------------------------------------------------------------------------string bb = "BCAx";            string aa = "AABBBCCC";            var r = bb.SelectMany(x => aa.Where(y => x == y)).GroupBy(y => y).OrderByDescending(x => x.Count());            var cc = string.Join("",  r.Select(y => y.Key));            Console.WriteLine(cc);//---------------------------------------------------------------------------------------------------------------------------------------------- string bb = "ABC";            string aa = "AABBBCCCC";            ConcurrentDictionary<string, int> cd = new ConcurrentDictionary<string, int>();             Parallel.For(0,aa.Length , i => {                var s = aa.Substring(i, 1);                cd.AddOrUpdate(s, 1, (key, value) => {                    return value += 1;                });            });    //cd.AddOrUpdate()里的s,1的s是key,1是要改变的增值,具体怎么增在后面的() => {} 里设置//----------------------------------------------------------------------------------------------------------------------------------------------var threadTwo = new Thread(Count);是创建一个线程,准备调用 Count 方法threadTwo.Start(8); 才是执行,并传递参数 8var threadThree = new Thread(() => CountNumbers(12)); 是创建一个线程,准备调用匿名方法 () => CountNumbers(12)//----------------------------------------------------------------------------------------------------------------------------------------------Sub Main()        Dim t(10) As Task        For index = 0 To 10            Dim i = index            t(index) = New Task(Function()                                    Dim s = fio(i)                                    Return s & "------------"                                End Function)            t(index).Start()        Next'For i = 0 To 10        '    Dim ii = i        '    t(i) = Task.Factory.StartNew(Function() As String        '                                     Dim s = fio(ii)        '                                     Return s & "="        '                                 End Function)        'Next        Task.WaitAll(t)        Console.ReadKey()    End Sub    Function fio(ByVal s As String) As String        s += "|ole"        Console.WriteLine(s)        Return s    End Function//----------------------------------------------------------------------------------------------------------------------------------------------static void a() { Console.WriteLine("a"); }        static void b() { Console.WriteLine("b"); }        static void c() { Console.WriteLine("c"); }        static void Main(string[] args)        {            Action someFun = new Action(a);            someFun += b;            someFun += c;            foreach (Action action in someFun.GetInvocationList())            {                //Code to exit these functions                action.Invoke();            }            Console.ReadKey();        }//----------------------------------------------------------------------------------------------------------------------------------------------\b(?!un)\w+(?<!un)\b    提取所有不以un开头和结尾的单词//----------------------------------------------------------------------------------------------------------------------------------------------Task<string> taskGetResult = Task<string>.Factory.StartNew(WriteSomethingAgain,(object)"");static string WriteSomethingAgain(object param)        {            for (int i = 0; i < 6; i++)            {                Console.WriteLine("write:" + i);                Thread.Sleep(100);                param = (string)param + i.ToString();            }            return (string)param;        }//----------------------------------------------------------------------------------------------------------------------------------------------using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace TaskDemo{    class Program    {        static void Main(string[] args)        {            CancellationTokenSource cancelTokenSource = new CancellationTokenSource();            Task task = Task.Factory.StartNew(Do,  cancelTokenSource.Token, cancelTokenSource.Token);            Thread.Sleep(1000);            try            {                cancelTokenSource.Cancel();                Thread.Sleep(10);                task.Wait();            }            catch (Exception ex)            {                if (task.IsCanceled)                {                    Console.WriteLine("ERR! Task has been canceled" + "\r\n" + ex.Message);                }            }            finally            {                task.Dispose();                cancelTokenSource.Dispose();            }            Console.WriteLine("Exiting Main...");            Console.ReadKey();        }        static void Do(object cancelToken)        {            for (int i = 0; i < 100; i++)            {                if (((CancellationToken)cancelToken).IsCancellationRequested)                {                    Console.WriteLine("Cancel han been requested");                    return;                    //注释break,去掉下面注释,程序会抛出异常,通过异常取消代码接收到取消事件发生。                    //token.ThrowIfCancellationRequested();                }                Console.WriteLine(i);                Thread.Sleep(500);            }        }    }}//----------------------------------------------------------------------------------------------------------------------------------------------None指定应使用默认行为。PreferFairness提示 TaskScheduler 以一种尽可能公平的方式安排任务,这意味着较早安排的任务将更可能较早运行,而较晚安排运行的任务将更可能较晚运行。LongRunning指定某个任务将是运行时间长、粗粒度的操作。 它会向 TaskScheduler 提示,过度订阅可能是合理的。AttachedToParent指定将任务附加到任务层次结构中的某个父级。//---------------------------------------------------------------------------------------------------------------------------------------------/private void button1_Click_1(object sender, EventArgs e)        {            for (int i = 0; i < 10; i++)            {                checkedListBox1.Items.Add("x" + i);            }        }        private void button2_Click(object sender, EventArgs e)        {            var pd = !checkedListBox1.GetItemChecked(0);            for (int i = 0; i < 10; i++)            {                checkedListBox1.SetItemChecked(i, pd);            }        }        private void button3_Click(object sender, EventArgs e)        {            string s = null;            for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)            {                //s += checkedListBox1.CheckedItems[i].ToString() + "\r\n";                s += checkedListBox1.GetItemText(checkedListBox1.CheckedItems[i]) + "\r\n";            }            MessageBox.Show(s );        }        private void button4_Click(object sender, EventArgs e)        {            for (int i = 0; i < 2; i++)            {                MessageBox.Show(checkedListBox1.GetSelected(i).ToString ());  //是否当前鼠标选中行            }        }        private void button5_Click(object sender, EventArgs e)        {            //checkedListBox1.Items.Clear();            //checkedListBox1.Items.RemoveAt(checkedListBox1.Items.Count);            checkedListBox1.Items.Remove(checkedListBox1.Items[0].ToString());  //只删除第一个符合的        }        private void button6_Click(object sender, EventArgs e)        {            if (checkedListBox1.SelectedIndex != -1)            {                MessageBox.Show(checkedListBox1.Items[checkedListBox1.SelectedIndex].ToString());            }        }//---------------------------------------------------------------------------------------------------------------------------------------------/folderBrowserDialog1.SelectedPath = System.Environment.CurrentDirectory;            //folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyDocuments;            folderBrowserDialog1.ShowNewFolderButton = true;            folderBrowserDialog1.Description = "请选择一个文件夹";              if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)            {                MessageBox.Show(folderBrowserDialog1.SelectedPath);            }//---------------------------------------------------------------------------------------------------------------------------------------------/public partial class Form1 : Form    {        public AppSettings appset;         public Form1()        {            InitializeComponent();            propertyGrid1.Size = new Size(300, 250);            appset = new AppSettings();            propertyGrid1.SelectedObject = appset;        }        private void button1_Click(object sender, EventArgs e)        {            MessageBox.Show(appset.ItemsInMRUList.ToString ());        }    }    public class AppSettings    {        private bool saveOnClose = true;        private string greetingText = "欢迎使用应用程序!";        private int itemsInMRU = 4;        private int maxRepeatRate = 10;        private bool settingsChanged = false;        private string appVersion = "1.0";        public bool SaveOnClose        {            get { return saveOnClose; }            set { saveOnClose = value; }        }        public string GreetingText        {            get { return greetingText; }            set { greetingText = value; }        }        public int MaxRepeatRate        {            get { return maxRepeatRate; }            set { maxRepeatRate = value; }        }        public int ItemsInMRUList        {            get { return itemsInMRU; }            set { itemsInMRU = value; }        }        public bool SettingsChanged        {            get { return settingsChanged; }            set { settingsChanged = value; }        }        public string AppVersion        {            get { return appVersion; }            set { appVersion = value; }        }    }  //---------------------------------------------------------------------------------------------------------------------------------------------/List<string> L1 = new List<string>();List<string> L2 = new List<string>();List<string> L3 = new List<string>();//-----------------------------------------------------------------------------------------------------------------------------------------------L1.Add("1");L1.Add("2");L1.Add("1");L2.Add("a");L2.Add("b");L2.Add("1");L1.AddRange(L2);//只简单追加L2到L1后L3 = L1.Concat(L2).ToList<string>();//*同上L3 = L1.Union(L2).ToList<string>();       //追加后总体上去重L3 = L1.Except(L2).ToList<string>();//在L1里去掉L2里有的然后导出L1.Sort();MessageBox.Show(L1.BinarySearch("1").ToString ());//只能用于排序后查询,速度超快static void Main(string[] args)          {              CancellationTokenSource cts = new CancellationTokenSource();              Task<int> t = new Task<int>(() => Add(cts.Token), cts.Token);              t.Start();              t.ContinueWith(TaskEnded);              //等待按下任意一个键取消任务              Console.ReadKey();              cts.Cancel();              Console.ReadKey();          }            static void TaskEnded(Task<int> task)          {              Console.WriteLine("任务完成,完成时候的状态为:");              Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);              Console.WriteLine("任务的返回值为:{0}", task.Result);          }            static int Add(CancellationToken ct)          {              Console.WriteLine("任务开始……");              int result = 0;              while (!ct.IsCancellationRequested)              {                  result++;                  Thread.Sleep(1000);              }              return result;          }  //-----------------------------------------------------------------------------------------------------------------------------------------------static void Main(string[] args)        {            CancellationTokenSource cts = new CancellationTokenSource();            //等待按下任意一个键取消任务              TaskFactory taskFactory = new TaskFactory();            Task[] tasks = new Task[3];            for (int i = 0; i < 3; i++)            {                //tasks[i] = new Task(() => Add(cts.Token));                tasks[i] = Task.Factory.StartNew(() => Add(cts.Token));//tasks[i] = (new TaskFactory()).StartNew (() => Add(cts.Token));                //tasks[i] = taskFactory.StartNew(() => Add(cts.Token));                //tasks[i].Start();            }            //CancellationToken.None指示TasksEnded不能被取消              taskFactory.ContinueWhenAll(tasks, TasksEnded,  CancellationToken.None );            Console.ReadKey();            cts.Cancel();            Console.ReadKey();          }        static void TasksEnded(Task[] a)        {            Console.WriteLine("所有任务已完成!");        }        static void Add(CancellationToken token)        {            Console.WriteLine("!");        } --------------------------------------------------------------------------------static void Main(string[] args)          {              CancellationTokenSource cts = new CancellationTokenSource();              //等待按下任意一个键取消任务              TaskFactory taskFactory = new TaskFactory();              Task[] tasks = new Task[]                  {                      taskFactory.StartNew(() => Add(cts.Token)),                      taskFactory.StartNew(() => Add(cts.Token)),                      taskFactory.StartNew(() => Add(cts.Token))                  };              //CancellationToken.None指示TasksEnded不能被取消              taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None);              Console.ReadKey();              cts.Cancel();              Console.ReadKey();          }  //-----------------------------------------------------------------------------------------------------------------------------------------------using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using Lordeo.Framework;using System.IO;namespace c_form12{    class A    {        public string 编号;        public DateTime 日期;        public TimeSpan 时间;        public double 数值;    }    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private static List<A> 读取(FileInfo file, DateTime 日期)        {            using (var fr = new StreamReader(file.FullName))            {                var res = new List<A>();                while (!fr.EndOfStream)                {                    var line = fr.ReadLine();                    if (line.Trim() != string.Empty)                    {                        var cs = line.Split(',');   //这部分调用你自己的解析程序,这里只是示例                        res.Add(new A                        {                            编号 = cs[0],                            日期 = 日期,                            时间 = TimeSpan.Parse(cs[1]),                            数值 = double.Parse(cs[2])                        });                    }                }                return res;            }        }        private void button1_Click(object sender, EventArgs e)        {            var 日期 = DateTime.Now.Date;            var dir = new DirectoryInfo("D:\\1\\datas_" + 日期.ToString("yyyyMMdd"));            if (dir.Exists)            {                var result = (from file in dir.EnumerateFiles().AsParallel()                               from data in 读取(file, 日期) select data).ToList();                MessageBox.Show(result.Count.ToString());            }        }    }}//-----------------------------------------------------------------------------------------------------------------------------------------------