当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


LINQ ToDictionary()用法及代码示例


在 LINQ 中,ToDictionary() 方法用于将列表/集合项(IEnumerable<T>)转换为新的字典对象(Dictionary<TKey,TValue>),它只会根据需要的值优化列表/集合项。

LINQ ToDictionary 方法的语法

这是使用 LINQ ToDictionary() 运算符的语法。

C# 代码

var student = objStudent.ToDictionary(x => x.Id, x => x.Name);

在上面的语法中,我们将 "objStudent" 的集合转换为字典对象并获取唯一需要的填充值(ID 和名称)。

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<Student> objStudent = new List<Student>()
            {
                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; }
         }
}

在上面的示例中,我们将 "objStudent" 的集合转换为字典对象并从两个值(ID 和 Name)中获取值。

输出:

LINQ ToDictionary() Method



相关用法


注:本文由纯净天空筛选整理自 LINQ ToDictionary() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。