本文概述
在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)中获取值。
输出