當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。