
LINQ ToDictionary() Method
In LINQ, ToDictionary operator is used to convert list/collection (IEnumerable<T>) items to a new dictionary object (Dictionary<TKey,TValue>) and it will optimize list/collection items by getting only required values.
Syntax of LINQ ToDictionary Operator
Following is the syntax of using LINQ ToDictionary operator to convert collection to new dictionary object.
C# Code
var student = objStudent.ToDictionary(x => x.Id, x => x.Name);
VB.NET Code
Dim student = objStudent.ToDictionary(Function(x) x.Id, Function(x) x.Name)
If you observe above syntax we are converting “objStudent” collection to dictionary object and getting only required field values (Id and Name).
Example of LINQ ToDictionary Operator
Following is the example of using LINQ ToDictionary operator to convert the collection to new dictionary object.
C# Code
using System;
using System.Linq;
using System.Collections.Generic;
namespace LINQExamples
{
classProgram
{
staticvoid Main(string[] args)
{
List<Student> objStudent = newList<Student>()
{
newStudent() { Id=1,Name = "Suresh Dasari", Gender = "Male",Location="Chennai" },
newStudent() { Id=2,Name = "Rohini Alavala", Gender = "Female", Location="Chennai" },
newStudent() { Id=3,Name = "Praveen Alavala", Gender = "Male",Location="Bangalore" },
newStudent() { Id=4,Name = "Sateesh Alavala", Gender = "Male", Location ="Vizag"},
newStudent() { Id=5,Name = "Madhav Sai", Gender = "Male", Location="Nagpur"}
};
var student = objStudent.ToDictionary(x => x.Id, x => x.Name);
foreach (var stud in student)
{
Console.WriteLine(stud.Key + "\t" + stud.Value);
}
Console.ReadLine();
}
}
classStudent
{
publicint Id { get; set; }
publicstring Name { get; set; }
publicstring Gender { get; set; }
publicstring Location { get; set; }
}
}
VB.NET Code
Module Module1
Sub Main()
Dim objStudent AsNew List(Of Student)() From {
New Student() With {.Id = 1, .Name = "Suresh Dasari", .Gender = "Male", .Location = "Chennai"},
New Student() With {.Id = 2, .Name = "Rohini Alavala", .Gender = "Female", .Location = "Chennai"},
New Student() With {.Id = 3, .Name = "Praveen Alavala", .Gender = "Male", .Location = "Bangalore"},
New Student() With {.Id = 4, .Name = "Sateesh Alavala", .Gender = "Male", .Location = "Vizag"},
New Student() With {.Id = 5, .Name = "Madhav Sai", .Gender = "Male", .Location = "Nagpur"}
}
Dim student = objStudent.ToDictionary(Function(x) x.Id, Function(x) x.Name)
ForEach stud In student
Console.WriteLine(Convert.ToString(stud.Key) + vbTab + stud.Value)
Next
Console.ReadLine()
EndSub
Class Student
PublicProperty Id() As Int32
Get
Return m_Id
EndGet
Set(ByVal value As Int32)
m_Id = value
EndSet
EndProperty
Private m_Id As Int32
PublicProperty Name() AsString
Get
Return m_Name
EndGet
Set(ByVal value AsString)
m_Name = value
EndSet
EndProperty
Private m_Name AsString
PublicProperty Gender() AsString
Get
Return m_Gender
EndGet
Set(ByVal value AsString)
m_Gender = value
EndSet
EndProperty
Private m_Gender AsString
PublicProperty Location() AsString
Get
Return m_Location
EndGet
Set(ByVal value AsString)
m_Location = value
EndSet
EndProperty
Private m_Location AsString
EndClass
EndModule
If you observe the above example we are converting “objStudent” collection to dictionary object and getting values from two fields (Id and Name)
Output of LINQ ToDictionary Operator Example
Following is the result of LINQ ToDictionary operator example.
1 Suresh Dasari
2 Rohini Alavala
3 Praveen Alavala
4 Sateesh Alavala
5 Madhav Sai
This is how we can use LINQ ToDictionary() method to convert list / collection items to new dictionary object in c#, vb.net with example.
C# ToDictionary MethodInvoke the ToDictionary extension from System.Linq to set keys and values with a lambda.
ToArray
ToList
Dictionary
IEnumerable
Part 1 We initialize an array of 4 integers, all odd numbers. These ints will be used to create a Dictionary.
Part 2 We invoke ToDictionary. The 2 arguments to ToDictionary are lambdas: the first sets each key, and the second sets each value.
Part 3 We specify a lambda. For keys, we use the ints from the array. For the values, we return "true" no matter what the key is.
Lambda
C# program that uses ToDictionary
Also Here we use the var keyword to simplify the syntax. Var helps reduce repetitive syntax.
Var
C# program that uses ToDictionary and List
IEqualityComparer. The ToDictionary method can receives a third argument, an IEqualityComparer. Here we use StringComparer.OrdinalIgnoreCase to create a case-insensitive dictionary.
C# program that uses IEqualityComparer
Info Thanks to Jeffrey for suggesting the StringComparer.OrdinalIgnoreCase argument for ToDictionary.
A summary. We used ToDictionary to transform a collection (such as an array or List) into a Dictionary collection. This provides constant-time lookups.
© sam allen.
see site info on the changelog.
C# (CSharp) Dictionary.ToDictionary Examples
ToDictionary method in C#
The ToDictionary method is an extension method in C# and converts a collection into Dictionary.
Firstly, create a string array −
string[] str = new string[] {"Car", "Bus", "Bicycle"};Now, use the Dictionary method to convert a collection to Dictionary −
str.ToDictionary(item => item, item => true);Here is the complete code −
Example
Live Demo
using System; using System.Collections.Generic; using System.Linq; class Demo { static void Main() { string[] str = new string[] {"Car", "Bus", "Bicycle"}; // key and value under ToDictionary var d = str.ToDictionary(item => item, item => true); foreach (var ele in d) { Console.WriteLine("{0}, {1}", ele.Key, ele.Value); } } }Output
Car, True Bus, True Bicycle, TrueExample todictionary c#
C# ToDictionary Method
ToDictionary converts a collection into a Dictionary.
It works on IEnumerable collections such as arrays and Lists. We can it to optimize performance—while retaining short and clear code. This method simplifies the demands of the code.
Example. First, this is an example of using the ToDictionary method in LINQ. We have built many Dictionary instances before. You simply loop over each element in your array and add it to the dictionary if it isn't already there.
Tip: LINQ gives us an extension method called ToDictionary, which can greatly simplify some code.
C# program that uses ToDictionary using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example integer array. int[] values = new int[] { 1, 3, 5, 7 }; // First argument is the key, second the value. Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true); // Display all keys and values. foreach (KeyValuePair<int, bool> pair in dictionary) { Console.WriteLine(pair); } } } Output [1, True] [3, True] [5, True] [7, True]ToDictionary has two arguments. There is a single argument and a two argument version of ToDictionary. The first argument uses lambda expressions to set the key, and the second for values. The Dictionary used here is an int Dictionary.
Int
Lambda expressions. Look at the "v => v" style lines. Lambda can be expressed as "goes to," meaning each item in the array goes to itself. There is more detailed information on this site about lambda expressions.
Lambdas
Example 2. You can use this method with a List of strings. Dictionaries are most useful for strings and string lookups. This allows us to use a number (hash code) in place of a string, greatly speeding things up.
Also: Here we use the var keyword to simplify the syntax. This reduces repetitive syntax.
Var
C# program that uses ToDictionary and List using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example with strings and List. List<string> list = new List<string>() { "cat", "dog", "animal" }; var animals = list.ToDictionary(x => x, x => true); if (animals.ContainsKey("dog")) { // This is in the Dictionary. Console.WriteLine("dog exists"); } } } Output dog existsLINQ. The benefit of LINQ is that it allows us to use fewer lines of boilerplate code to insert elements into a Dictionary. This reduces lines of code and typos. It is elegant and fits well with other LINQ code.
Note: LINQ methods are significantly slower, but will scale equally well. Some programmers may not understand lambda syntax.
Caution: Sometimes, using ToDictionary may prevent you from combining the loop with another operation, also leading to inefficient code.
Summary. We used LINQ and the ToDictionary extension method to quickly transform one kind of collection such as an array or List into a Dictionary collection. This provides constant-time lookups.
Note: This is useful in some cases where performance is not critical and short code is more important.
Also: For an alternative to the ToDictionary method, please see the ToLookup method.
ToLookup
© - TheDeveloperBlog.com | Visit CSharpDotNet.com for more C# Dot Net Articles
C# Language LINQ Queries ToDictionary
Example
The LINQ method can be used to generate a collection based on a given source.
In this example, the single argument passed to is of type , which returns the key for each element.
This is a concise way to perform the following operation:
You can also pass a second parameter to the method, which is of type and returns the to be added for each entry.
It is also possible to specify the that is used to compare key values. This can be useful when the key is a string and you want it to match case-insensitive.
Note: the method requires all keys to be unique, there must be no duplicate keys. If there are, then an exception is thrown: If you have a scenario where you know that you will have multiple elements with the same key, then you are better off using instead.
Similar news:
- Binghamton university acceptance rate
- Genie scout 16
- Small boats for sale
- John bizon
- Walking dead 150 review
- Rhino mobile detailing
- Club pogo.com login
- 2017 subaru sti oil capacity