I have a table with 2 columns defined as varchar(50): Column1 and Column2. I want to return a dictionary of <string, string>
where each row is in the dictionary and where Column1 is the key and Column2 is the value. This is what I have:
public Dictionary<string, string> LoadAllTheDataFromDB()
{
using (MyDC TheDC = new MyDC())
{
return (from c in TheTable
select new Dictionary<string, string>()
{
//stuck here
}).FirstOrDefault();
}
}
How do I make it that the dictionary is filled?
Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. 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 can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.
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.
There are only two return types for a Linq query. It's either a single concrete object or a single anonymous type object that is returned. It can also be a List<T> of concrete objects or anonymous type objects that are returned in a collection.
Try this:
var dict = TheTable.Select( t => new { t.Col1, t.Col2} )
.ToDictionary( t => t.Col1, t => t);
Remember in select lambda you will perform projection and create some anonymous object. Then in ToDictionary
you will pass two parameters: First Parameter is a lambda to specify the key; in code above we are choosing Col1
to be the key. Second parameter is a lambda to specify the value; in code above we are choosing the object itself to be the value.
If you want the value to be an anonymous type, change the 2nd lambda like this:
ToDictionary( t => t.Col1, t => new { t.Col2 });
If you want the value to be a type you have defined, change the 2nd lambda like this:
ToDictionary( t => t.Col1, t => new YourType { Prop1 = t.Col2 });
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