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>?
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.
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.
LINQ provides you three different ways to write a LINQ query in C# or VB.
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.
You need to specify the values for the Dictionary
var d2 = q.ToDictionary(p => p.NickName, p => p.Name);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With