目录
Json转为实体类,生成代码
Newtonsoft.Json中JObject的使用
分页计算 总页数、当前页数据集合
Task 定时器
事件Event
打印 DataTable 到控制台
获取 DataTable 的所有列名
DataTable 转换为实体类
单例模式 新写法
随机数
DataSet 和 DataTable 的用法
获取项目的名称
去掉字符串中的特殊字符
字符串只保留字母和数字
DataTable 基本用法
json 如下:
{
"Name": "Jack",
"Age": 34,
"Colleagues": [{
"Name": "Tom",
"Age": 44
}, {
"Name": "Abel",
"Age": 29
}]
}
打开网站:JSON转C#实体类-BeJSON.com
输入json,点击生成实体类就会生成实体类代码了
这里看下实体类
//如果好用,请收藏地址,帮忙分享。
public class ColleaguesItem
{
///
///
///
public string Name { get; set; }
///
///
///
public int Age { get; set; }
}
public class Root
{
///
///
///
public string Name { get; set; }
///
///
///
public int Age { get; set; }
///
///
///
public List Colleagues { get; set; }
}
我们用 Newtonsoft.Json 插件序列化一下,就可以将Json中的数据赋值到这个实体类中了,真的非常的方便,不过,我测试过于复杂的Json时还是有点问题的,自己手动改一下就好了
案例1
json
{
"Name": "Jack",
"Age": 34,
"Colleagues": [{
"Name": "Tom",
"Age": 44
}, {
"Name": "Abel",
"Age": 29
}]
}
代码
using Newtonsoft.Json.Linq;
using System;
namespace JObject案例
{
class Program
{
static void Main(string[] args)
{
string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
JObject jObject1 = JObject.Parse(json);
string name = jObject1["Name"].ToString();
string age = jObject1["Age"].ToString();
string colleagues1_name = jObject1["Colleagues"][0]["Name"].ToString();
string colleagues1_age = jObject1["Colleagues"][0]["Age"].ToString();
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(colleagues1_name);
Console.WriteLine(colleagues1_age);
Console.ReadKey();
}
}
}
运行
案例2
json
{
"ID": 1,
"Name": "张三",
"Favorites": ["吃饭", "睡觉"]
}
代码
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace JObject案例
{
class Program
{
static void Main(string[] args)
{
string json = "{\"ID\":1,\"Name\":\"张三\",\"Favorites\":[\"吃饭\",\"睡觉\"]}";
JObject jObject1 = JObject.Parse(json);
Console.WriteLine(jObject1["ID"]);
Console.WriteLine(jObject1["Name"]);
Console.WriteLine(jObject1["Favorites"][0]);
Console.WriteLine(jObject1["Favorites"][1]);
Console.ReadKey();
}
}
}
运行
案例3
json
{
"input": {
"size": 193156,
"type": "image/png"
},
"output": {
"size": 59646,
"type": "image/png",
"width": 487,
"height": 284,
"ratio": 0.3088,
"url": "https://www.baidu.com"
}
}
代码
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;
namespace JObject案例
{
class Program
{
static void Main(string[] args)
{
string json = "{\"input\":{\"size\":193156,\"type\":\"image/png\"},\"output\":{\"size\":59646,\"type\":\"image/png\",\"width\":487,\"height\":284,\"ratio\":0.3088,\"url\":\"https://www.baidu.com\"}}";
JObject jObject1 = JObject.Parse(json);
Console.WriteLine(jObject1["input"]["size"]);
Console.WriteLine(jObject1["input"]["type"]);
Console.WriteLine(jObject1["output"]["size"]);
Console.WriteLine(jObject1["output"]["type"]);
Console.ReadKey();
}
}
}
运行
案例4
json
{
"code": "SUCCESS",
"msg": null,
"data": [{
"id": 31783735,
"residentInfoId": 2000099151,
"doctorId": "89bd0716-f916-4e51-93f7-4d416830f03c"
}]
}
代码
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;
namespace JObject案例
{
class Program
{
static void Main(string[] args)
{
string json = "{\"code\":\"SUCCESS\",\"msg\":null,\"data\":[{\"id\":31783735,\"residentInfoId\":2000099151,\"doctorId\":\"89bd0716-f916-4e51-93f7-4d416830f03c\"}]}";
JObject jObject1 = JObject.Parse(json);
Console.WriteLine(jObject1["code"]);
Console.WriteLine(jObject1["SUCCESS"]);
Console.WriteLine(jObject1["data"][0]["id"]);
Console.WriteLine(jObject1["data"][0]["residentInfoId"]);
Console.WriteLine(jObject1["data"][0]["doctorId"]);
Console.ReadKey();
}
}
}
运行
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test4
{
class Program
{
static void Main(string[] args)
{
int AllCount = 9;
Console.WriteLine("总个数:" + AllCount);
int page = AllCount / PageCount;
int remainder = AllCount % PageCount;
Console.WriteLine("页数:" + page);
Console.WriteLine("余数:" + remainder);
int totalPage = remainder > 0 ? page + 1 : page;
Console.WriteLine("总页数:" + totalPage);
//获取第二页索引的起点和结束点
int index = 2;
Console.WriteLine(string.Format("获取第{0}页数据",index));
int start = (index * PageCount) - PageCount;
int end = (index * PageCount) - 1;
Console.WriteLine(string.Format("起点:{0},结束点:{1},index:{2}", start, end, index));
Console.WriteLine("========================================");
//添加随机数
Random random = new Random();
for (int i = 0; i < 17; i++)
{
MyList.Add(random.Next(10, 1000).ToString());
}
Print(MyList);
//获取当页数据集合
Console.WriteLine("获取第3页数据");
List myList = GetIndexList(3);
Print(myList);
Console.ReadKey();
}
public static List MyList = new List();
//一页的个数
public static int PageCount = 8;
///
/// 获取当页的数据集合
///
///
///
public static List GetIndexList(int index)
{
if (MyList.Count <= 0) return null;
int page = MyList.Count / PageCount;
int remainder = MyList.Count % PageCount;
int allPage = remainder > 0 ? page + 1 : page;
if (index > allPage) return null;
int start = (index * PageCount) - PageCount;
int end = (index * PageCount) - 1;
if (end > MyList.Count) end = MyList.Count -1;
List list = new List();
for (int i = start; i <= end; i++)
{
list.Add(MyList[i]);
}
if(list.Count > 0)
return list;
return null;
}
public static void Print(List list)
{
if (list == null || list.Count <= 0) return;
string msg = string.Empty;
for (int i = 0; i < list.Count; i++)
{
msg += list[i] + ",";
}
Console.WriteLine(msg);
}
}
}
输出结果:
总个数:9
页数:1
余数:1
总页数:2
获取第2页数据
起点:8,结束点:15,index:2
====
393,318,19,71,597,684,59,892,134,773,657,32,264,231,296,257,733,
获取第3页数据
733,
注意===线下面的数据是随机数,每次运行结果不一样,
获取的是第3页,而当前总个数是17,一页是8个,第3页刚好是最后一个,可以看到,计算没有问题
使用C#的定时器,在使用多线程时会出现,回调方法不执行的情况,用Task作为定时器也是个不错的选择。
异步延时执行代码:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Task延时执行
{
class Program
{
static void Main(string[] args)
{
//调用方法1
Task.Factory.StartNew(TimerTask);
Thread.Sleep(2000);
//调用方法2 这里也可以使用Lambda表达式
Task.Run(TimerTask);
Console.ReadKey();
}
private static async Task TimerTask()
{
//异步方式等待2秒
await Task.Delay(TimeSpan.FromSeconds(2));
Console.WriteLine("等待2秒");
}
}
}
假设需要一个定时器,循环的执行,看下面代码
代码:
using System;
using System.Threading.Tasks;
namespace Task循环执行
{
class Program
{
private static bool isStop = false;
private static int index = 0;
static void Main(string[] args)
{
isStop = true;
Task.Run(DosomeThingAsync);
Console.ReadKey();
}
private static async Task DosomeThingAsync()
{
while (isStop)
{
await Task.Delay(TimeSpan.FromSeconds(2));
index++;
Console.WriteLine("index:"+index);
if(index >= 5)
{
isStop = false;//退出循环
index = 0;
}
}
}
}
}
运行:
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Events
{
public class Bridegroom
{
//自定义委托
public delegate void MarryHandler(string msg);
//使用自定义委托定义事件,事件名MarryEvent
public event MarryHandler MarryEvent;
public void onMarriageComing(string msg)
{
if(MarryEvent != null)
{
//触发事件
MarryEvent(msg);
}
}
}
public class Friend
{
public string Name;
public Friend(string name)
{
Name = name;
}
public void SendMessage(string mess)
{
//处理事件
Console.WriteLine(this.Name + "收到了,到时候准时参加!");
}
}
class Program
{
static void Main(string[] args)
{
Bridegroom bridegroom = new Bridegroom();
Friend friend1 = new Friend("张三");
Friend friend2 = new Friend("李四");
Friend friend3 = new Friend("王五");
bridegroom.MarryEvent += new Bridegroom.MarryHandler(friend1.SendMessage);
bridegroom.MarryEvent += new Bridegroom.MarryHandler(friend2.SendMessage);
bridegroom.onMarriageComing("朋友们,结婚了");
Console.ReadKey();
}
}
}
代码:
//打印所有列名
string columnName = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
//columnName += dataTable.Columns[i].ColumnName + " | ";
columnName += string.Format("{0}({1}) | ", dataTable.Columns[i].ColumnName, i);
}
Console.WriteLine(columnName);
//打印每一行的数据
foreach (DataRow row in dataTable.Rows)
{
string columnStr = string.Empty;
foreach (DataColumn column in dataTable.Columns)
{
columnStr += row[column] + " | ";
}
Console.WriteLine(columnStr);
}
对于 打印每一行的数据,如果你不想用 foreach 循环,还可以使用下面写法,效果一样的
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string columnStr = string.Empty;
for (int j = 0; j < dataTable.Columns.Count; j++)
{
columnStr += dataTable.Rows[i][j] + " | ";
}
Console.WriteLine(columnStr);
}
代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable("Datas");
DataColumn dc = new DataColumn();
dc.AutoIncrement = true;//自动增加
dc.AutoIncrementSeed = 1;//起始为1
dc.AutoIncrementStep = 1;//步长为1
dc.AllowDBNull = false;//是否允许空值
//添加列
dc = dt.Columns.Add("ID", Type.GetType("System.String"));
dc = dt.Columns.Add("Product", Type.GetType("System.String"));
dc = dt.Columns.Add("Version", Type.GetType("System.String"));
dc = dt.Columns.Add("Description", Type.GetType("System.String"));
if (dt.Columns.Count > 0)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.WriteLine("列名:" + dt.Columns[i].ColumnName);
}
}
}
运行:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
///
/// 将DataTable数据源转换成实体类
///
public static class ConvertTool
{
///
/// DataTable转换成实体类
///
///
///
///
public static List TableToEntity(DataTable dt) where T : class, new()
{
List list = new List();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = new T();
PropertyInfo[] pArray = entity.GetType().GetProperties();
foreach (PropertyInfo p in pArray)
{
if (dt.Columns.Contains(p.Name))
{
if (!p.CanWrite) continue;
var value = row[p.Name];
if (value != DBNull.Value)
{
Type targetType = p.PropertyType;
Type convertType = targetType;
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//可空类型
NullableConverter nullableConverter = new NullableConverter(targetType);
convertType = nullableConverter.UnderlyingType;
}
if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value.ToString()))
{
value = Convert.ChangeType(value, convertType);
}
switch (convertType.FullName)
{
case "System.Decimal":
p.SetValue(entity, Convert.ToDecimal(value), null);
break;
case "System.String":
p.SetValue(entity, Convert.ToString(value), null);
break;
case "System.Int32":
p.SetValue(entity, Convert.ToInt32(value), null);
break;
case "System.Int64":
p.SetValue(entity, Convert.ToInt64(value), null);
break;
case "System.Int16":
p.SetValue(entity, Convert.ToInt16(value), null);
break;
case "System.Double":
p.SetValue(entity, Convert.ToDouble(value), null);
break;
case "System.DateTime":
p.SetValue(entity, Convert.ToDateTime(value), null);
break;
default:
p.SetValue(entity, value, null);
break;
}
}
}
}
list.Add(entity);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if(list.Count > 0)
return list;
else
return null;
}
}
传统写法,适用于Winform,控制台,在Unity3d里面不太合适这种方式。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
Test.Instance.SayHi();
Console.ReadKey();
}
}
public class Test
{
private static Test instance;
public static Test Instance
{
get
{
if (instance == null)
instance = new Test();
return instance;
}
}
public void SayHi()
{
Console.WriteLine("oh my god");
}
private Test()
{
}
}
}
新写法:
新写法和传统写法比起来要少写一些代码,效果是一样的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
Test.Instance.SayHi();
Console.ReadKey();
}
}
public class Test
{
public static Test Instance;
public void SayHi()
{
Console.WriteLine("oh my god");
}
private Test()
{
}
static Test()
{
Instance = new Test();
}
}
}
随机整数和随机小数
public class RandomNum
{
///
/// 获取随机整数
///
/// 你需要几个随机数
/// 下限
/// 上限
/// 返回随机数的数组,长度根据个数而定
public static int[] GetRandomArray(int count, int minNum, int maxNum)
{
int[] randomArr = new int[count];
Random r = new Random();
for (int j = 0; j < count; j++)
{
int i = r.Next(minNum, maxNum + 1);
int num = 0;
for (int k = 0; k < j; k++)
{
if (randomArr[k] == i) num = num + 1;
}
if (num == 0)
randomArr[j] = i;
else
j = j - 1;
}
return randomArr;
}
///
/// 获取随机浮点数
///
/// 下限
/// 上限
/// 小数点保留位数
/// 随机的浮点数
public static double GetRandomNumber(double minimum, double maximum, int Len)
{
Random random = new Random();
//注意:不用间隔时间,使用for循环获取,返回的几个随机数会一模一样
System.Threading.Thread.Sleep(1);
return Math.Round(random.NextDouble() * (maximum - minimum) + minimum, Len);
}
}
代码:
//DataSet 的 Table 可以装多个表单(DataTable)
DataSet ds = new DataSet();
//创建一个表单
DataTable dt = new DataTable("Name");
//添加列
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Sex", typeof(string)));
dt.Columns.Add(new DataColumn("Addr", typeof(string)));
//添加一行数据到列中
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["Name"] = "张三";
dr["Sex"] = "不男不女";
dr["addr"] = "泰国";
//添加一行数据到表单中
dt.Rows.Add(dr);
//将表单添加到DataSet的表单列表中
ds.Tables.Add(dt);
//显示到界面中
//dataGridView1.DataSource = ds.Tables[0];
//和上行代码效果一样
dataGridView1.DataSource = dt;
效果:
一、控制台
通过 Assembly.GetEntryAssembly().GetName() 可以得到项目名称,版本号等信息,如下:
ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
获取项目名称:
代码:
Console.WriteLine(Assembly.GetEntryAssembly().GetName().Name);
输出:
ConsoleApp1
二、Windows Form
Application.ProductName
方案一:
string except_chars = ": ‘ ! @ # % … & * ( ^ & ¥ , 。 , .)$";
string src = "就是包含: 这些‘字符 包含空格)都要$去掉么?";
string result = Regex.Replace(src, "[" + Regex.Escape(except_chars) + "]", "");
方案二:
//只保留字母、数字 和汉字
string strAfter= Regex.Replace(strBefor, @"[^a-zA-Z0-9\u4e00-\u9fa5\s]", "");
代码:
public static string GetNumberAlpha(string source)
{
string pattern = "[A-Za-z0-9]";
string strRet = "";
MatchCollection results = Regex.Matches(source, pattern);
foreach (var v in results)
{
strRet += v.ToString();
}
return strRet;
}
创建一个窗体程序:
添加两个组件:
1.组件名:dataGridView1
给组件添加要给自动排序的方法,在CellPainting双击
2.button
双击自动添加点击事件
全部代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LJYZN_105
{
public partial class Form3 : Form
{
DataTable dt = null;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
Table();
}
private void Table()
{
//DataTable dt = new DataTable("Datas");
//DataColumn dc1 = new DataColumn("商品编号");
//DataColumn dc2 = new DataColumn("商品名称");
//DataColumn dc3 = new DataColumn("商品重量");
//DataColumn dc4 = new DataColumn("商品价格");
//DataColumn dc5 = new DataColumn("购买数量");
//dt.Columns.Add(dc1);
//dt.Columns.Add(dc2);
//dt.Columns.Add(dc3);
//dt.Columns.Add(dc4);
//dt.Columns.Add(dc5);
dt = new DataTable("Datas");
DataColumn dc = new DataColumn();
dc.AutoIncrement = true;//自动增加
dc.AutoIncrementSeed = 1;//起始为1
dc.AutoIncrementStep = 1;//步长为1
dc.AllowDBNull = false;//是否允许空值
//添加列
dc = dt.Columns.Add("ID", Type.GetType("System.String"));
dc = dt.Columns.Add("Product", Type.GetType("System.String"));
dc = dt.Columns.Add("Version", Type.GetType("System.String"));
dc = dt.Columns.Add("Description", Type.GetType("System.String"));
DataRow newRow;
//第一种方式
newRow = dt.NewRow();
newRow["ID"] = "1";
newRow["Product"] = "南瓜";
newRow["Version"] = "2.0";
newRow["Description"] = "熟了";
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow["ID"] = "2";
newRow["Product"] = "西瓜";
newRow["Version"] = "3.0";
newRow["Description"] = "熟了";
dt.Rows.Add(newRow);
//第二种方式
dt.Rows.Add(new object[] {"3", "冬瓜", "4.0", "没熟" });
//绑定数据
this.dataGridView1.DataSource = dt;
//设置列的宽度
this.dataGridView1.Columns[0].Width = 50;
//查找是否存在某个值
bool res = IsIncludeData(dt, "Product", "西瓜");
Console.WriteLine("===========查找结果:" + res);
//查找在那一行
dt.PrimaryKey = new System.Data.DataColumn[] { dt.Columns["Product"] };
DataRow dataRow = dt.Rows.Find("南瓜");
if (dataRow != null)
{
Console.WriteLine("===========查找列并获取版本:" + dataRow["Version"]);
//将查到的值重新赋值
dataRow["Version"] = 100;
//删除南瓜这行
dt.Rows.Remove(dataRow);
}
//DataTable dt = new DataTable();
//dt.Rows[i];//已知
//dt.Rows[--i];//上一行
//dt.Rows[++i];//下一行
//获取这一列是那一行
int rowNum = FindRowIndex(dataRow);
Console.WriteLine("===========行号:" + rowNum);
}
///
/// 设置DataGridView组件的列序号自动增加
///
///
///
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 && e.RowIndex >= 0) // 绘制 自动序号
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
Rectangle vRect = e.CellBounds;
vRect.Inflate(-2, 2);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), e.CellStyle.Font, vRect, e.CellStyle.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
e.Handled = true;
}
// ----- 其它样式设置 -------
if (e.RowIndex % 2 == 0)
{ // 行序号为双数(含0)时
e.CellStyle.BackColor = Color.White;
}
else
{
e.CellStyle.BackColor = Color.Honeydew;
}
e.CellStyle.SelectionBackColor = Color.Gray; // 选中单元格时,背景色
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //单位格内数据对齐方式
}
///
/// 判断DataTable中的列是否存在某个值
///
/// DataTable类
/// 列名
/// 要查找的值字符串
/// 包含这个值返回true,不包含返回false
public bool IsIncludeData(DataTable dt, String columnName, string fieldData)
{
if (dt == null)
{
return false;
}
else
{
if (dt.Select(columnName + "='" + fieldData + "'").Length > 0)
{
return true;
}
else
{
return false;
}
}
}
///
/// 获取行号
///
///
///
private int FindRowIndex(DataRow dr)
{
return dr.Table.Rows.IndexOf(dr);
}
private void button1_Click(object sender, EventArgs e)
{
dt.Rows.Add(new object[] { "茄子", "5.0", "半熟" });
}
}
}
运行:
图中的100是通过查找获取到行(DataRow),并修改它的值
下面的按钮,可以随时向DataGridView内添加数据,自动放到表格的最下面一行
这里我们只需要改dt内数据,就可以随时显示最新的数据了
end