Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a LINQ query resulting in a Dictionary?

 public class Person {     public string NickName{ get; set; }     public string Name{ get; set; } }  var pl = new List<Person>;  var q = from p in pl         where p.Name.First() == 'A'         orderby p.NickName         select new KeyValuePair<String, String>(p.NickName, p.Name);  var d1 = q.ToList(); // Gives List<KeyValuePair<string, string>> var d2 = q.ToDictionary(); // Does not compile 

How to get Dictionary<string, string>?

like image 466
Ivan Avatar asked Dec 19 '12 09:12

Ivan


People also ask

How do you write a query in LINQ?

There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.

What does LINQ query return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

How many ways can you write LINQ queries?

LINQ provides you three different ways to write a LINQ query in C# or VB.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


2 Answers

You need to specify the values for the Dictionary

var d2 = q.ToDictionary(p => p.NickName, p => p.Name); 
like image 158
Neil Knight Avatar answered Sep 20 '22 18:09

Neil Knight


A dictionary cannot contain multiple equal keys, so you should ensure (or know) that this is not the case. You could use GroupBy to ensure it:

Dictionary<string, string> dict = pl         .Where(p => p.Name.First() == 'A')         .GroupBy(p => p.NickName)         .ToDictionary(g => g.Key, g => g.First().Name);  
like image 30
Tim Schmelter Avatar answered Sep 18 '22 18:09

Tim Schmelter