Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Linq Query Result to Dictionary

I want to add some rows to a database using Linq to SQL, but I want to make a "custom check" before adding the rows to know if I must add, replace or ignore the incomming rows. I'd like to keep the trafic between the client and the DB server as low as possible and minimize the number of queries.

To do this, I want to fetch as little information as required for the validation, and only once at the beginning of the process.

I was thinking of doing something like this, but obviously, it doesn't work. Anyone have an idea?

Dictionary<int, DateTime> existingItems =      (from ObjType ot in TableObj         select (new KeyValuePair<int, DateTime>(ot.Key, ot.TimeStamp))     ) 

What I'd like to have at the end would be a Dictionary, without having to download the whole ObjectType objects from TableObject.

I also considered the following code, but I was trying to find a proper way:

List<int> keys = (from ObjType ot in TableObj orderby ot.Key select ot.Key).ToList<int>(); List<DateTime> values = (from ObjType ot in TableObj orderby ot.Key select ot.Value).ToList<int>(); Dictionary<int, DateTime> existingItems = new Dictionary<int, DateTime>(keys.Count); for (int i = 0; i < keys.Count; i++) {     existingItems.Add(keys[i], values[i]); } 
like image 377
Tipx Avatar asked Jun 05 '09 01:06

Tipx


People also ask

Can use Linq for dictionary?

In LINQ, ToDictionary() Method is used to convert the items of list/collection(IEnumerable<T>) to new dictionary object (Dictionary<TKey,TValue>) and it will optimize the list/collection items by required values only.

Are LINQ queries thread safe?

They're not thread safe.

What is Linq in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


2 Answers

Try using the ToDictionary method like so:

var dict = TableObj.Select( t => new { t.Key, t.TimeStamp } )                    .ToDictionary( t => t.Key, t => t.TimeStamp ); 
like image 148
4 revs, 4 users 69% Avatar answered Sep 28 '22 02:09

4 revs, 4 users 69%


Looking at your example, I think this is what you want:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp); 
like image 23
BFree Avatar answered Sep 28 '22 02:09

BFree