linqy的个人博客分享 http://blog.sciencenet.cn/u/linqy

博文

C# 不同数组之间的转换Array、List、Dictionary

已有 4141 次阅读 2019-2-18 17:17 |系统分类:科研笔记

 Student[] StudentArray = new Student[3];

            //创建创建3个student对象,并赋值给数组的每一个元素           

            StudentArray[0] = new Student()

            {

                Id = 203,

                Name = "Tony Stark",

                Gender = "Male"

            };

            StudentArray[1] = new Student()

            {

                Id = 205,

                Name = "Hulk",

                Gender = "Male"

            };

            StudentArray[2] = new Student()

            {

                Id = 210,

                Name = "Black Widow",

                Gender = "Female"

            };

            //Array to List

            List<Student> StudentList = StudentArray.ToList<Student>();


            //List to array

            Student[] ListToArray = StudentList.ToArray<Student>();


            //Array to Dictionary

            Dictionary<int, Student> StudentDictionary = StudentArray.ToDictionary(key => key.Id, Studentobj => Studentobj);


            //Dictionary to Array

            Student[] DictionaryToArray = StudentDictionary.Values.ToArray();


            //List to Dictionary

            Dictionary<int, Student> ListToDictionary = StudentList.ToDictionary(key => key.Id, value => value);


            //Dictionary to List

            List<Student> DictionaryToList = StudentDictionary.Values.ToList();

            foreach (Student student in DictionaryToList)

            {

                Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);

            }

            string[] testAarray = new string[2];

            testAarray[0] = "123";

            testAarray[1] = "231";

            Dictionary<int, string> strDic = testAarray.ToDictionary(arrayItem => System.Array.IndexOf(testAarray, arrayItem), arrayItem => arrayItem);

                        

           // ArrayList

            ArrayList alist = new ArrayList();

            alist.Add("123");

            alist.Add("122");

            alist.Add("121");

            alist.TrimToSize();//压缩数组空间容量的大小到数组的实际容量


            Console.ReadKey();




https://wap.sciencenet.cn/blog-3134052-1162874.html

上一篇:[转载]Android解决 NDK not configured问题
下一篇:[转载]导入一个外部的Android App项目需要修改哪些配置文件?
收藏 IP: 221.214.6.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-29 17:19

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部