c# 基本 用法
来源:互联网 发布:怎么修改淘宝上的地址 编辑:程序博客网 时间:2024/06/07 19:20
First and FirstOrDefault
1 #regionEnumberable First() or FirstOrDefault()
2 /// <summary> 3 /// 返回序列中的第一个元素;如果序列中不包含任何元素,则返回默认值。 4 /// 如果 source 为空,则返回 default(TSource);否则返回 source 中的第一个元素。 5 /// ArgumentNullException sourcevalue 为 null。 6 /// </summary> 7 public static void FunFirstOrDefault() 8 { 9 //FirstOrDefault()10 string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };11 // string[] names = { }; // string 类型的默认值是空12 13 int[] sexs = { 100, 229, 44, 3, 2, 1 };14 // int[] sexs = { }; // 因为int 类型的默认值是0. 所以当int[] 数组中没有任何元素时。default value is 0; 如果有元素,则返回第一个元素15 16 //原方法: public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source); // 扩展了IEnumerable<TSource> 接口17 //string namevalue = names.FirstOrDefault(); // string IEnumerable<string>.FirstOrDefault<string>();18 int sexvalue = sexs.FirstOrDefault(); // int IEnumerable<int>.FirstOrDefault<string>();19 //string namevalue = names.DefaultIfEmpty("QI").First();20 string namevalue = names.FirstOrDefault();21 Console.WriteLine("FirstOrDefault(): default(TSource) if source is empty; otherwise, the first element in source:{0}", namevalue);22 23 24 }25 26 /// <summary>27 /// 返回序列中的第一个元素。 28 /// 如果 source 中不包含任何元素,则 First<TSource>(IEnumerable<TSource>) 方法将引发异常29 /// ArgumentNullException sourcevalue 为 null。30 // InvalidOperationException 源序列为空。31 /// </summary>32 public static void FunFirst()33 {34 //First()35 string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };36 // string[] names = { };37 38 int[] sexs = { 100, 229, 44, 3, 2, 1 };39 //int[] sexs = { };40 int fsex = sexs.First();41 string fname = names.First(); // 如果序列中没有元素则会发生,InvalidOperationException 异常。 源序列为空。42 43 Console.WriteLine("First(): Returns the first element of a sequence : {0}", fname);44 45 }46 #endregion
以上是我在本地验证的code.
需要注意的是:
这都是扩展了IEnumerable 这个接口。
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);
First 和 FirstOrDefault 最大的区别在于。 当集合(这个集合可以是:Arry,List,等等)中没有元素的时候。 First 会报异常 InvalidOperationException 源序列为空。
而 FirstOrDefault 则不会。
c#计时方法
- //秒表方法一:
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (int i = 0; i < 10000; i++)
- {
- }
- sw.Stop();
- MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
- //当前时间减去开始时间方法二:
- DateTime begintime = DateTime.Now;
- for (int i = 0; i < 10000; i++)
- {
- }
- TimeSpan ts = DateTime.Now.Subtract(begintime);
- MessageBox.Show(ts.TotalMilliseconds.ToString());
#region 1.获得md5值
public static string GetMD5(string msg)
{
StringBuilder sb = new StringBuilder();
using (MD5 md5=MD5.Create())
{
byte[] buffer = Encoding.UTF8.GetBytes(msg);
byte[] newB = md5.ComputeHash(buffer);
foreach (byte item in newB)
{
sb.Append(item.ToString("x2"));
}
}
return sb.ToString();
}
#endregion
#region 2获得一个文件的MD5
public static string GetFileMD5(string filepath)
{
StringBuilder sb = new StringBuilder();
using (MD5 md5=MD5.Create())
{
using (FileStream fs=File.OpenRead(filepath))
{
byte[] newB = md5.ComputeHash(fs);
foreach (byte item in newB)
{
sb.Append(item.ToString("x2"));
}
}
}
return sb.ToString();
}
#endregion
C#MD5加密解密
using System.Security.Cryptography;
using System.IO;
using System.Text;
///MD5加密
public string MD5Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach(byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
///MD5解密
public string MD5Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for(int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(),CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
-------------------------------------------------------------------------------
using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
class DES
{
// 创建Key
public string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
// 加密字符串
public string EncryptString(string sInputString, string sKey)
{
byte [] data = Encoding.UTF8.GetBytes(sInputString);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
// 解密字符串
public string DecryptString(string sInputString, string sKey)
{
string [] sInput = sInputString.Split("-".ToCharArray());
byte [] data = new byte[sInput.Length];
for(int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
}
class Test
{
static void Main()
{
DES des = new DES();
string key = des.GenerateKey();
string s0 = "中国软件 - csdn.net";
string s1 = des.EncryptString(s0, key);
string s2 = des.DecryptString(s1, key);
Console.WriteLine("原串: [{0}]", s0);
Console.WriteLine("加密: [{0}]", s1);
Console.WriteLine("解密: [{0}]", s2);
}
}
/* 程序输出:
原串: [中国软件 - csdn.net]
加密: [E8-30-D0-F2-2F-66-52-14-45-9A-DC-C5-85-E7-62-9B-AD-B7-82-CF-A8-0A-59-77]
解密: [中国软件 - csdn.net]
*/
从网页上提取用户邮箱为每个邮箱发送一封邮件
WebClient wc = new WebClient();
string html = wc.DownloadString("http://laiba.tianya.cn/tribe/showArticle.jsp?groupId=93803&articleId=255105449041749990113803&curPageNo=1&h=p_1255011420000");
string reg = "[a-zA-Z0-9_\\.]+@[a-zA-Z0-9_\\.]+\\.[a-zA-Z0-9_\\.]+";
MatchCollection matches = Regex.Matches(html, reg);
List<string> listEmail = new List<string>();
foreach (Match mt in matches)
{
listEmail.Add(mt.Groups[0].Value);
}
//------------------以下是创建邮件和发送邮件的过程----------------------
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("****@qq.com");
mail.To.Add("*****@qq.com");
foreach (string email in listEmail)
{
mail.To.Add(email);
}
mail.SubjectEncoding = Encoding.UTF8;
mail.Subject = "测试邮件";
mail.BodyEncoding = Encoding.UTF8;
mail.Body = "c#程序控制控!!!!!!!";
//创建html的邮件内容
AlternateView view = AlternateView.CreateAlternateViewFromString("文字在这里,也可以是<h1>html</h1>的代码<img src=\"cid:img001\" />", Encoding.UTF8, "text/html");
LinkedResource lr = new LinkedResource(@"E:\图片\pics\雷锋.jpg");
lr.ContentId = "img001";
view.LinkedResources.Add(lr);
mail.AlternateViews.Add(view);
//为邮件添加附件
Attachment at = new Attachment(@"D:\项目\chinatt315\members\qiyetupian\batianshengtai01.jpg");
Attachment at1 = new Attachment(@"D:\项目\chinatt315\2011315hd\qytp\piyopiyo2.jpg");
mail.Attachments.Add(at);
mail.Attachments.Add(at1);
SmtpClient smtp = new SmtpClient("pop.qq.com");
smtp.Credentials = new NetworkCredential("用户名", "密码$");
//为每个邮箱发送2封相同的邮件
for (int i = 0; i < 2; i++)
{
smtp.Send(mail);
}
Console.WriteLine("发送成功");
}
catch (Exception ex)
{
Console.WriteLine("发送失败!"+ex.Message);
}
Console.ReadKey();
- C# DataTable基本用法
- C# ArrayList 基本用法
- c# 基本 用法
- C#委托基本用法
- C# List基本用法
- C#属性的基本用法
- C#委托的基本用法
- C# ListView控件基本用法
- C# ListView控件基本用法
- C# DataSet的基本用法
- C# 数组的基本用法
- C# List<T>基本用法
- C# DataSet的基本用法
- C#中foreach基本用法
- C# DataSet的基本用法
- c#中List基本用法
- c# BackgroundWorker的基本用法
- C# 中Command 基本用法
- 泡在网上的日子
- 罗网统计:软件系统升级公告
- CCF真题--数字排序
- 【南大软院大神培养计划】JS再接触
- Android 窗口添加机制系列2-Dialog,PopupWindow,Toast
- c# 基本 用法
- c语言俄罗斯方块
- AFN监测网络状态
- RAC DATAGUARD primary listener
- Linux下的proc目录详解
- 基于 platform 总线的设备驱动编写模式:
- ls- 查看linux 文件的大小
- 驱动模型
- C语言扫雷