Linq ToDictionary()方法

Linq ToDictionary()方法 首页 / LinQ入门教程 / Linq ToDictionary()方法

在LINQ中,ToDictionary()方法用于将列表/集合的项(IEnumerable<;T&>;)转换为新的字典对象(Dictionary<;TKey,TValue&>t;),并且只根据所需的值对列表/集合项进行优化。

LINQ ToDictionary方法的语法

下面是使用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).

ToDictionary方法示例

下面是使用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
            List objStudent = 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).

输出:

LINQ ToDictionary() Method




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Python -〔尹会生〕

OpenResty从入门到实战 -〔温铭〕

MongoDB高手课 -〔唐建法(TJ)〕

Kafka核心源码解读 -〔胡夕〕

OAuth 2.0实战课 -〔王新栋〕

性能优化高手课 -〔尉刚强〕

大数据经典论文解读 -〔徐文浩〕

去无方向的信 -〔小麥〕

高并发系统实战课 -〔徐长龙〕

好记忆不如烂笔头。留下您的足迹吧 :)