Convertir Linq Query Result en Diccionario


Quiero agregar algunas filas a una base de datos usando Linq to SQL, pero quiero hacer una "comprobación personalizada" antes de agregar las filas para saber si debo agregar, reemplazar o ignorar las filas que vienen. Me gustaría mantener el tráfico entre el cliente y el servidor de base de datos lo más bajo posible y minimizar el número de consultas.

Para hacer esto, quiero obtener tan poca información como sea necesaria para la validación, y solo una vez al comienzo del proceso.

Estaba pensando en hacer algo como esto, pero obviamente, no funciona. Alguien tiene una idea?

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

Lo que me gustaría tener al final sería un diccionario, sin tener que descargar todos los objetos ObjectType de TableObject.

También consideré el siguiente código, pero estaba tratando de encontrar una manera adecuada:

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]);
}
Author: JoshL, 2009-06-05

4 answers

Intenta usar el método ToDictionary así:

var dict = TableObj.Select( t => new { t.Key, t.TimeStamp } )
                   .ToDictionary( t => t.Key, t => t.TimeStamp );
 521
Author: tvanfosson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-01 19:16:23

Mirando tu ejemplo, creo que esto es lo que quieres:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
 105
Author: BFree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-05 02:53:48

Intente lo siguiente

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

O la versión inferenciada de tipo completo

var existingItems = TableObj.ToDictionary(x => x.Key);
 7
Author: JaredPar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-05 01:48:11

Usar espacio de nombres

using System.Collections.Specialized;

Hacer instancia de DataContext Clase

LinqToSqlDataContext dc = new LinqToSqlDataContext();

Use

OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);

Para recuperar los valores utilice el espacio de nombres

   using System.Collections;

ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;

String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];

keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);

for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();
 0
Author: Salman Mushtaq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-16 12:59:37