本文概述
- LINQ ToDictionary方法的语法
- ToDictionary方法的示例
LINQ ToDictionary方法的语法 【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 ListList<
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 studentforeach (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元素运算符
- LINQ AsEnumrable()方法
- LINQ OfType()方法
- LINQ ToLookup()方法
- LINQ Cast()方法
- LINQ ToArray()方法
- LINQ ToList()方法
- LINQ skip操作符
- LINQ TakeWhile分区运算符