fre*_*hie 12 c# asp.net linq-to-sql
我有一个表,其中2列定义为varchar(50):Column1和Column2.我想返回一个字典,<string, string>其中每行在字典中的位置,其中Column1是键,Column2是值.这就是我所拥有的:
public Dictionary<string, string> LoadAllTheDataFromDB()
{
using (MyDC TheDC = new MyDC())
{
return (from c in TheTable
select new Dictionary<string, string>()
{
//stuck here
}).FirstOrDefault();
}
}
Run Code Online (Sandbox Code Playgroud)
如何填写字典?
Cod*_*shi 33
试试这个:
var dict = TheTable.Select( t => new { t.Col1, t.Col2} )
.ToDictionary( t => t.Col1, t => t);
Run Code Online (Sandbox Code Playgroud)
请记住,在select lambda中,您将执行投影并创建一些匿名对象.然后在ToDictionary你将传递两个参数:First Parameter是一个lambda来指定键; 在上面的代码中,我们选择Col1成为关键.第二个参数是lambda来指定值; 在上面的代码中,我们选择对象本身作为值.
如果您希望该值为匿名类型,请更改第二个lambda,如下所示:
ToDictionary( t => t.Col1, t => new { t.Col2 });
Run Code Online (Sandbox Code Playgroud)
如果您希望该值是您定义的类型,请更改第二个lambda,如下所示:
ToDictionary( t => t.Col1, t => new YourType { Prop1 = t.Col2 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16186 次 |
| 最近记录: |