首页 > 编程语言 >C#高级

C#高级

时间:2024-03-03 12:00:10浏览次数:22  
标签:HostId Console C# List 高级 item WriteLine new

//字典类
List<Dictionary<string, string>> dics = new List<Dictionary<string, string>>();
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("name1", "张三");
pairs.Add("name2", "李四");
dics.Add(pairs);
List<string> vs = new List<string>();
int f = 0;
foreach (Dictionary<string, string> item in dics)
{
if (item.Keys.Contains("name1"))
{
var testA = item.Values.ToList()[f];
vs.Add(testA);
}
f++;
}

//哈希表(Hashtable):
Hashtable hashtable = new Hashtable();
hashtable.Add(100, "西安");
//能转换成功
string hashvalue = hashtable[100] as string;
if (hashvalue != null)
{
Console.WriteLine(hashvalue);
}
// 转换失败,获取的值为null,但不会抛出错误。
StreamReader reader = hashtable[100] as StreamReader;
if (reader == null)
{
Console.WriteLine("西安不是StreamReader型");
}
// 也可以直接获取object值,再做判断
object value2 = hashtable[100];
if (value2 is string)
{
Console.Write("这个是字符串类型: ");
Console.WriteLine(value2);
}

//找出每个集合中都包含的元素:
Console.WriteLine("找出每个集合中都包含的元素:");
List<string[]> listA = new List<string[]>();
string[] itemA = { "1", "2", "3", "4", "5" };
string[] itemB = { "1", "5", "2" };
string[] itemC = { "2", "3", "7", "5" };
string[] itemD = { "4", "5", "8", "3", "2" };
listA.Add(itemA);
listA.Add(itemB);
listA.Add(itemC);
listA.Add(itemD);
string[] containArray = new string[] { };
for (int i = 0; i < listA.Count - 1; i++)
{
if (i == 0)
{
containArray = listA[i];
}
containArray = containArray.Where(x => listA[i + 1].Contains(x)).ToArray();
}
foreach (var item in containArray)
{
Console.Write(item + " ");
}
Console.WriteLine("\n");


//集合(GroupBy):
List<DbInfo> infos = new List<DbInfo>()
{
new DbInfo(){ DbId=1,HostId=1 },
new DbInfo(){ DbId=2,HostId=2 },
new DbInfo(){ DbId=3,HostId=1 },
new DbInfo(){ DbId=4,HostId=2 },
new DbInfo(){ DbId=5,HostId=1 },
new DbInfo(){ DbId=6,HostId=2 },
new DbInfo(){ DbId=7,HostId=1 },
new DbInfo(){ DbId=8,HostId=3 },
};
//分组统计
//var result = infos.GroupBy(d => d.HostId);
//var ee = result.Where(d => d.Key == 1).FirstOrDefault() == null ? 0 : result.Where(d => d.Key == 1).FirstOrDefault().Count();
//Console.WriteLine(ee);
//Console.ReadLine();
//分组前
Console.WriteLine("分组前:");
foreach (var item in infos)
{
Console.WriteLine(" HostId:" + item.HostId + " DbId:" + item.DbId);
}
//分组后
Console.WriteLine("分组后:");
List<DbInfo> dbInfos = new List<DbInfo>();
var result = infos.ToLookup(d => d.HostId);
foreach (var item in result)
{
var info = item.FirstOrDefault();
DbInfo dbInfo = new DbInfo();
dbInfo.HostId = info.HostId;
dbInfo.Infos = item.ToList();
dbInfos.Add(dbInfo);
}
foreach (var item in dbInfos)
{
Console.WriteLine("HostId:" + item.HostId);
string arr = "[\n";
foreach (var info in item.Infos)
{
arr += " HostId:" + info.HostId + " DbId:" + info.DbId + "\n";
}
arr += "]";
Console.WriteLine(arr);
}
Console.ReadLine();

//赋值写法(各种数据类型):
int[] intA = { 0, 1, 2 };
string[] strA = { "0", "1", "2" };
List<int> intList = new List<int> { 0, 1, 2 };
List<string> strList = new List<string> { "0", "1", "2" };
Entities aa = new Entities { Name = "Higa, Sidney", Pets = new List<string> { "0", "1", "2" } };
List<Student> list = new List<Student>
{
new Student{Name="YJingLee",Age="18"},
new Student{Name="YJingLer",Age="19"},
};
list.ForEach(x =>
{
Console.WriteLine(x.Name + " " + x.Age);
});
List<PersonA> aList = new List<PersonA>() {
new PersonA("张三", "18"),
new PersonA("张四", "19"),
new PersonA("张五", "20"),
new PersonA("张六", "21")
};
foreach (var item in aList)
{
Console.Write(item.Name + "-" + item.Age);
Console.WriteLine();
}

//合并多个集合到一个:
Entities[] petOwners =
{
new Entities {Name = "张三", Pets = new List<string> {"11", "11"}},
new Entities {Name = "李四", Pets = new List<string> {"22", "22"}},
new Entities {Name = "王五", Pets = new List<string> {"33", "33"}}
};
IEnumerable<string> resultA = petOwners.SelectMany(petOwner => petOwner.Pets);
foreach (string pet in resultA)
{
Console.WriteLine(pet);
}
Console.WriteLine("\n");

//Dictionary<int,string>类型:
Console.WriteLine("Dictionary<int,string>泛型");
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(0, "C#");
myDictionary.Add(1, "C++");
myDictionary.Add(2, "C");
myDictionary.Add(3, "VB");
if (myDictionary.ContainsKey(0))
{
Console.WriteLine("Key:{0},Value:{1}", 0, myDictionary[0]);
}
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;
foreach (int key in keyCol)
{
Console.WriteLine("Key = {0}", key);
}
Dictionary<int, string>.ValueCollection valueCol = myDictionary.Values;
foreach (string value in valueCol)
{
Console.WriteLine("Value = {0}", value);
}
//移除指定的键值By Remove方法
myDictionary.Remove(0);
if (myDictionary.ContainsKey(0))
{
Console.WriteLine("Key:{0},Value:{1}", 0, myDictionary[0]);
}
else
{
Console.WriteLine("不存在 Key : 0");
}
Console.WriteLine("\n");

//计算程序运行时间:
Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(3000);
sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds);
Console.WriteLine("\n");

//反射:
Student nc = new Student();
Type t = nc.GetType();
PropertyInfo[] pis = t.GetProperties();
foreach (PropertyInfo pi in pis)
{
Console.WriteLine("反射:" + pi.Name);
}
Console.WriteLine("\n");

//查看类中的构造方法:
nc = new Student();
t = nc.GetType();
ConstructorInfo[] ci = t.GetConstructors(); //获取类的所有构造函数
foreach (ConstructorInfo c in ci) //遍历每一个构造函数
{
ParameterInfo[] ps = c.GetParameters(); //取出每个构造函数的所有参数
foreach (ParameterInfo pi in ps) //遍历并打印所该构造函数的所有参数
{
Console.Write(pi.ParameterType.ToString() + " " + pi.Name + ",");
}
Console.WriteLine();
}
//字段赋值
nc = new Student();
t = nc.GetType();
object obj = Activator.CreateInstance(t);
//取得ID字段
FieldInfo fi = t.GetField("Id");
//给ID字段赋值
fi.SetValue(obj, "k001");
//取得MyName属性
PropertyInfo pi1 = t.GetProperty("Name");
//给MyName属性赋值
pi1.SetValue(obj, "grayworm", null);
PropertyInfo pi2 = t.GetProperty("content");
pi2.SetValue(obj, "hi.baidu.com/grayworm", null);
//取得show方法
MethodInfo mi = t.GetMethod("Show");
//调用show方法
var invoke = mi.Invoke(obj, null);
//输出show的内容
Console.WriteLine(invoke);
Console.WriteLine("\n");

//C#映射:
var person = new PersonA("张三", "12", "男");
var student = new Student();
//第一个类型转成第二个类型
var mapper = ObjectMapperManager.DefaultInstance.GetMapper<PersonA, Student>();
mapper.Map(person, student);
Console.WriteLine("姓名:" + student.Name + ",年龄:" + student.Age);

标签:HostId,Console,C#,List,高级,item,WriteLine,new
From: https://www.cnblogs.com/wangtiantian/p/18049794

相关文章

  • 并发编程之asyncio模块
    引言Python中的协程:协程是一种轻量级的用户级线程,它在单线程内执行,不会阻塞主线程,可以在多个任务间轻松地切换,因此可以用于实现异步I/O操作。协程的实现方式与生成器非常相似,通过使用yield语句来暂停和恢复执行。协程可以与asyncio库配合使用,来实现异步I/O操作。这种方式可以......
  • RabbitMQ、RocketMQ、Kafka区别
    引言1、队列应用场景:MQ(MessageQueue,消息队列)消息队列在实际应用中常用的使用场景(优点):异步处理,应用解耦,流量削锋和消息通讯四个场景。2、目前使用较多的消息队列:有老牌的ActiveMQ、RabbitMQ,ZeroMQ,炙手可热的Kafka,MetaMQ,阿里巴巴的RocketMQ。3、如何选型(目前现状):......
  • docker Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is th
    应该是docker异常关闭导致无法启动。步骤1参考《https://www.cnblogs.com/langgeligelang/p/14607658.html》执行systemctldaemon-reloadsystemctlrestartdocker如果失败,提示Authorizationnotavailable.Checkifpolkitserviceisrunningorseedebugmessagef......
  • C++第二课 while循环
    循环while(条件){   循环体}#include<bits/stdc++.h>usingnamespacestd;intmain(){   inti,s;   i=1;   s=0;   while(i<=100)   {      s=s+i;      i=i+1;   }   cout<<s<<endl;   return0;}计算1......
  • 并发编程之条件Condition
    条件Condition(了解)使得线程等待,只有满足某条件时,才释放n个线程importthreadingdefrun(n):con.acquire()con.wait()print("runthethread:%s"%n)con.release()if__name__=='__main__':con=threading.Condition()foriinra......
  • 绕过 UAC 相关的技术
    UAC(用户账户控制)是Windows操作系统中的一项安全功能,旨在帮助防止未经授权的更改系统设置和应用程序的行为。UAC通过提示用户确认或提升权限来减少恶意软件对系统的影响。然而,有人可能试图绕过UAC以获取更高的权限,这种行为是不推荐的,并且可能违反法律。以下是您提到的一些可能......
  • 【PG】查询 正在vacuum对象的(持续)时间
    --https://dataegret.com/2017/10/deep-dive-into-postgres-stats-pg_stat_progress_vacuum/SELECTp.pid,now()-a.xact_startASduration,coalesce(wait_event_type||'.'||wait_event,'f')ASwaiting,CASEWHENa.query~*'^autovacuum......
  • 「java.util.concurrent并发包」之 Unsafe
    一unsafe介绍Unsafe是位于sun.misc包下的一个类,主要提供一些用于执行低级别、不安全操作的方法,如直接访问系统内存资源、自主管理内存资源等,这些方法在提升Java运行效率、增强Java语言底层资源操作能力方面起到了很大的作用。但由于Unsafe类使Java语言拥有了类似C......
  • 是学习c++还是java?
    上高中时,自己第一次接触到学校的中华学习机和苹果机,当时中华学习机上可以进行basic编程,那时候自己其实就爱上编程,但是没有人指点,也学习不得法,所以就没有进行下去!大学时,自己的主攻专业并不是计算机,但是学习了《计算机基础》和《c程序设计》,前者主要学习dos命令和wps文字处理,后者主......
  • Blazor使用QuickGrid
    @usingMicrosoft.AspNetCore.Components.QuickGrid<PageTitle>PromotionGrid</PageTitle><h1>PromotionGridExample</h1><QuickGridItems="@people"><PropertyColumnProperty="@(p=>p.PersonId)"Sor......