在LINQ中,ToDictionary()方法用于将列表/集合的项(IEnumerable<;T&>;)转换为新的字典对象(Dictionary<;TKey,TValue&>t;),并且只根据所需的值对列表/集合项进行优化。
下面是使用LINQ ToDictionary()运算符的语法。
C#代码
var student = objStudent.ToDictionary(x => x.Id, x => x.Name);
In the above syntax, we are converting the collection of "objStudent" to dictionary object and getting the only required filled value (ID and Name).
下面是使用LINQ ToDictionary运算符将集合转换为新字典对象的示例。
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //Create a object objStudent of Student class and add the information of student in the List ListobjStudent = new List () { new Student() { Id=1,Name = "Vinay Tyagi", Gender = "Male",Location="Chennai" }, new Student() { Id=2,Name = "Vaishali Tyagi", Gender = "Female", Location="Chennai" }, new Student() { Id=3,Name = "Montu Tyagi", Gender = "Male",Location="Bangalore" }, new Student() { Id=4,Name = "Akshay Tyagi", Gender = "Male", Location ="Vizag"}, new Student() { Id=5,Name = "Arpita Rai", Gender = "Male", Location="Nagpur"} }; /*here with the help of ToDictionary() method we are converting the colection of information in the form of dictionary and will fetch only the required information*/ var student = objStudent.ToDictionary(x => x.Id, x => x.Name); //foreach loop is used to print the information of the student foreach (var stud in student) { Console.WriteLine(stud.Key + "\t" + stud.Value); } Console.ReadLine(); } } class Student { public int Id { get; set; } public string Name { get; set; } public string Gender { get; set; } public string Location { get; set; } } }
In the above example, we are converting the collection of "objStudent" to dictionary objects and getting the values from the two values (ID and Name).
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)