Todictionary c# example

Todictionary c# example DEFAULT

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.

Sours: https://www.tutlane.com/tutorial/linq/linq-todictionary-method

C# ToDictionary MethodInvoke the ToDictionary extension from System.Linq to set keys and values with a lambda.

ToDictionary.This extension method converts a collection into a Dictionary. It works on IEnumerable collections such as arrays and Lists.

ToArray

ToList

Some uses.We can use ToDictionary to optimize performance—while retaining short and clear code. This method simplifies the demands of the code.

Dictionary

IEnumerable

First example.Building up dictionaries can require a significant amount of code. When we use ToDictionary, we can use less code to create a Dictionary.

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

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Part 1: create example integer array.int[] values = new int[] { 1, 3, 5, 7}; // Part 2: call ToDictionary.// Part 3: specify lambda as argument.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); } } }[1, True] [3, True] [5, True] [7, True]
String example.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. Var helps reduce 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"}; varanimals = list.ToDictionary(x =>x, x =>true); if (animals.ContainsKey("dog")) { // This is in the Dictionary.Console.WriteLine("dog exists"); } } }dog exists

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

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> list = new List<string>() { "cat", "bird"}; // Create case-insensitive dictionary.var pets = list.ToDictionary(x => x, x => true, StringComparer.OrdinalIgnoreCase); if (pets.ContainsKey("CAT")) { Console.WriteLine("CAT exists"); } } }CAT exists
Notes, LINQ.ToDictionary allows us to use fewer lines of code to insert elements into a Dictionary. This method is elegant and fits well with other LINQ code.

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.

Sours: https://www.dotnetperls.com/todictionary
  1. Seville 8 drawer storage cart
  2. Power barrel mhw
  3. Evo 2016 smash 4

C# (CSharp) Dictionary.ToDictionary Examples

/// <summary> /// Initializes a new instance of the <see cref="Lexer" /> class. /// </summary> public Lexer() { // regex special characters (should be escaped if needed): .$^{[(|)*+?\ var patterns = new Dictionary<TokenType, string> { {TokenType.AND, @"&&"}, {TokenType.OR, @"\|\|"}, {TokenType.LEFT_BRACKET, @"\("}, {TokenType.RIGHT_BRACKET, @"\)"}, {TokenType.GE, @">="}, {TokenType.LE, @"<="}, {TokenType.GT, @">"}, {TokenType.LT, @"<"}, {TokenType.EQ, @"=="}, {TokenType.NEQ, @"!="}, {TokenType.NOT, @"!"}, {TokenType.NULL, @"null"}, {TokenType.COMMA, @","}, {TokenType.INC, @"\+{2}"}, // Despite the fact our language does not support ++ and -- prefix/postfix operations yet, these unary tokens are explicitly designated as illegal. We're detecting them to prevent unification which is done for consecutive plus or minus operators (e.g. + + - - +-+- => +). {TokenType.DEC, @"\-{2}"}, // Unification of such unary operators breaks compatibility - such mixed 1++ + 2 operations are illegal in both C# and JavaScript (since we control C# side there is not pain here, but JavaScript would fail since we're sending raw expressions to client-side). {TokenType.ADD, @"\+"}, {TokenType.SUB, @"-"}, {TokenType.MUL, @"\*"}, {TokenType.DIV, @"/"}, {TokenType.FLOAT, @"[]*\.[]+(?:[eE][\+-]?[]+)?"}, // , e-2 {TokenType.INT, @"[]+"}, {TokenType.BOOL, @"(?:true|false)"}, {TokenType.STRING, @"(['])(?:\\\1|.)*?\1"}, // '', 'John\'s cat' {TokenType.FUNC, @"[a-zA-Z_]+(?:(?:(?:\[[]+\])?\.[a-zA-Z_])?[a-zA-Z_]*)*(?:\[[]+\])?"} // field, field.field, arr[0], func() }; RegexMap = patterns.ToDictionary( kvp => kvp.Key, kvp => new Regex(string.Format("^{0}", kvp.Value))); // in general, for compiled version of regular expressions their construction and initialization time is amortized out over many runs }
Sours: https://csharp.hotexamples.com/examples/-/Dictionary/ToDictionary/php-dictionary-todictionary-method-examples.html
Convert Linq Query Result to Dictionary

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, True
Sours: https://www.tutorialspoint.com/todictionary-method-in-chash

Example todictionary c#

C# ToDictionary Method

This C# tutorial shows how to use the ToDictionary extension from System.Linq.

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 exists

LINQ. 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

Sours: https://thedeveloperblog.com/todictionary
C# Dictionaries - Sorting By Values and ToDictionary() Method

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.






Sours: https://riptutorial.com/csharp/example//todictionary

Similar news:

C# (CSharp) System.ToDictionary Examples

static PinMapping() { var mapping = /* Value is not used but required for anonymous type */ new[]{ new { Processor = ProcessorPin.Pin0, Connector = ConnectorPin.P1Pin03 }}; if (GpioConnectionSettings.BoardConnectorRevision == 1) mapping = new[] { new {Processor = ProcessorPin.Pin0, Connector = ConnectorPin.P1Pin3}, new {Processor = ProcessorPin.Pin1, Connector = ConnectorPin.P1Pin5}, new {Processor = ProcessorPin.Pin4, Connector = ConnectorPin.P1Pin7}, new {Processor = ProcessorPin.Pin7, Connector = ConnectorPin.P1Pin26}, new {Processor = ProcessorPin.Pin8, Connector = ConnectorPin.P1Pin24}, new {Processor = ProcessorPin.Pin9, Connector = ConnectorPin.P1Pin21}, new {Processor = ProcessorPin.Pin10, Connector = ConnectorPin.P1Pin19}, new {Processor = ProcessorPin.Pin11, Connector = ConnectorPin.P1Pin23}, new {Processor = ProcessorPin.Pin14, Connector = ConnectorPin.P1Pin8}, new {Processor = ProcessorPin.Pin15, Connector = ConnectorPin.P1Pin10}, new {Processor = ProcessorPin.Pin17, Connector = ConnectorPin.P1Pin11}, new {Processor = ProcessorPin.Pin18, Connector = ConnectorPin.P1Pin12}, new {Processor = ProcessorPin.Pin21, Connector = ConnectorPin.P1Pin13}, new {Processor = ProcessorPin.Pin22, Connector = ConnectorPin.P1Pin15}, new {Processor = ProcessorPin.Pin23, Connector = ConnectorPin.P1Pin16}, new {Processor = ProcessorPin.Pin24, Connector = ConnectorPin.P1Pin18}, new {Processor = ProcessorPin.Pin25, Connector = ConnectorPin.P1Pin22} }; else if (GpioConnectionSettings.BoardConnectorRevision == 2) mapping = new[] { new {Processor = ProcessorPin.Pin2, Connector = ConnectorPin.P1Pin3}, new {Processor = ProcessorPin.Pin3, Connector = ConnectorPin.P1Pin5}, new {Processor = ProcessorPin.Pin4, Connector = ConnectorPin.P1Pin7}, new {Processor = ProcessorPin.Pin7, Connector = ConnectorPin.P1Pin26}, new {Processor = ProcessorPin.Pin8, Connector = ConnectorPin.P1Pin24}, new {Processor = ProcessorPin.Pin9, Connector = ConnectorPin.P1Pin21}, new {Processor = ProcessorPin.Pin10, Connector = ConnectorPin.P1Pin19}, new {Processor = ProcessorPin.Pin11, Connector = ConnectorPin.P1Pin23}, new {Processor = ProcessorPin.Pin14, Connector = ConnectorPin.P1Pin8}, new {Processor = ProcessorPin.Pin15, Connector = ConnectorPin.P1Pin10}, new {Processor = ProcessorPin.Pin17, Connector = ConnectorPin.P1Pin11}, new {Processor = ProcessorPin.Pin18, Connector = ConnectorPin.P1Pin12}, new {Processor = ProcessorPin.Pin27, Connector = ConnectorPin.P1Pin13}, new {Processor = ProcessorPin.Pin22, Connector = ConnectorPin.P1Pin15}, new {Processor = ProcessorPin.Pin23, Connector = ConnectorPin.P1Pin16}, new {Processor = ProcessorPin.Pin24, Connector = ConnectorPin.P1Pin18}, new {Processor = ProcessorPin.Pin25, Connector = ConnectorPin.P1Pin22}, new {Processor = ProcessorPin.Pin28, Connector = ConnectorPin.P5Pin3}, new {Processor = ProcessorPin.Pin29, Connector = ConnectorPin.P5Pin4}, new {Processor = ProcessorPin.Pin30, Connector = ConnectorPin.P5Pin5}, new {Processor = ProcessorPin.Pin31, Connector = ConnectorPin.P5Pin6} }; else //if (GpioConnectionSettings.BoardConnectorRevision == 3) mapping = new[] { new {Processor = ProcessorPin.Pin2, Connector = ConnectorPin.P1Pin3}, new {Processor = ProcessorPin.Pin3, Connector = ConnectorPin.P1Pin5}, new {Processor = ProcessorPin.Pin4, Connector = ConnectorPin.P1Pin7}, new {Processor = ProcessorPin.Pin5, Connector = ConnectorPin.P1Pin29}, new {Processor = ProcessorPin.Pin6, Connector = ConnectorPin.P1Pin31}, new {Processor = ProcessorPin.Pin7, Connector = ConnectorPin.P1Pin26}, new {Processor = ProcessorPin.Pin8, Connector = ConnectorPin.P1Pin24}, new {Processor = ProcessorPin.Pin9, Connector = ConnectorPin.P1Pin21}, new {Processor = ProcessorPin.Pin10, Connector = ConnectorPin.P1Pin19}, new {Processor = ProcessorPin.Pin11, Connector = ConnectorPin.P1Pin23}, new {Processor = ProcessorPin.Pin12, Connector = ConnectorPin.P1Pin32}, new {Processor = ProcessorPin.Pin13, Connector = ConnectorPin.P1Pin33}, new {Processor = ProcessorPin.Pin14, Connector = ConnectorPin.P1Pin8}, new {Processor = ProcessorPin.Pin15, Connector = ConnectorPin.P1Pin10}, new {Processor = ProcessorPin.Pin16, Connector = ConnectorPin.P1Pin36}, new {Processor = ProcessorPin.Pin17, Connector = ConnectorPin.P1Pin11}, new {Processor = ProcessorPin.Pin18, Connector = ConnectorPin.P1Pin12}, new {Processor = ProcessorPin.Pin19, Connector = ConnectorPin.P1Pin35}, new {Processor = ProcessorPin.Pin20, Connector = ConnectorPin.P1Pin38}, new {Processor = ProcessorPin.Pin21, Connector = ConnectorPin.P1Pin40}, new {Processor = ProcessorPin.Pin22, Connector = ConnectorPin.P1Pin15}, new {Processor = ProcessorPin.Pin23, Connector = ConnectorPin.P1Pin16}, new {Processor = ProcessorPin.Pin24, Connector = ConnectorPin.P1Pin18}, new {Processor = ProcessorPin.Pin25, Connector = ConnectorPin.P1Pin22}, new {Processor = ProcessorPin.Pin26, Connector = ConnectorPin.P1Pin37}, new {Processor = ProcessorPin.Pin27, Connector = ConnectorPin.P1Pin13}, }; processorMappings = mapping.ToDictionary(p => p.Connector, p => p.Processor); connectorMappings = mapping.ToDictionary(p => p.Processor, p => p.Connector); }
Sours: https://csharp.hotexamples.com/examples/-/System/ToDictionary/php-system-todictionary-method-examples.html


430 431 432 433 434