LINQ to SQL查询结果ToDictionary? [英] LINQ to SQL Query Result ToDictionary?

查看:205
本文介绍了LINQ to SQL查询结果ToDictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在尝试将LINQ查询的结果加载到字典中.我想添加到字典中的SQL数据库中有两列,一列是Key,另一列是Value.

我使用以下查询从SQL Server检索信息.

Hi Guys,
I am trying to load the results of a LINQ Query into a dictionary. I have two columns in a SQL Database that i would like to add to a dictionary, one column is to be the Key and the other is the Value.

I use the below query to retrieve the information from SQL Server.

var query = from s in SongDC.songs
            orderby s.song_ORDER ascending
            select s;



如何将上述查询的结果加载到字典中?

我希望将s.song_ORDER作为键,将s.song_ID作为值,并希望能够实现下面的功能……更好.



How can I load the results of the above query into a dictionary?

I would like s.song_ORDER to be the Key and s.song_ID to be the Value and was hoping to able to something like what is below... only better.

Dictionay<int, int> testDictionary = new Dictionary<int, int>();

foreach(var s in query)
{
   testDictionary.Add(s.song_ORDER, s.song_ID);
}



感谢您的帮助,
Alex



Thanks for your help,
Alex

推荐答案

使用几个lambda将调用添加到ToDictionary,您会很高兴.

Add the call to ToDictionary with a couple of lambdas and you''re golden.

var query = (from s in SongDC.songs
             orderby s.song_ORDER ascending
             select s).ToDictionary(s => s.song_ORDER, s=> s.song_ID);



ToDictionary()帮助器采用两个lambda表达式. s表示所讨论的对象(这里是LINQ表达式的返回类型,因此是Song对象).第一个函数返回song_ORDER,它成为键.第二个返回的是song_ID,这是字典中KeyPairValue的值.

干杯.



The ToDictionary() helper takes two lambda expressions. s represents the object in question (here, the return type of the LINQ expression, so, a Song object). The first function returns the song_ORDER which becomes the key. The second returns the song_ID, which is the value for the KeyPairValue in the dictionary.

Cheers.


这篇关于LINQ to SQL查询结果ToDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆