[英]Returning a Dictionary<string, string> from a linq query
I have a table with 2 columns defined as varchar(50): Column1 and Column2. 我有一个表,其中2列定义为varchar(50):Column1和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. 我想返回
<string, string>
的字典,其中每一行都在字典中,其中Column1是键,Column2是值。 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? 如何填写字典?
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. 请记住,在select lambda中,您将执行投影并创建一些匿名对象。 Then in
ToDictionary
you will pass two parameters: First Parameter is a lambda to specify the key; 然后在
ToDictionary
您将传递两个参数:First Parameter是一个指定键的lambda; in code above we are choosing Col1
to be the key. 在上面的代码中,我们选择
Col1
作为关键。 Second parameter is a lambda to specify the value; 第二个参数是lambda来指定值; 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: 如果您希望该值为匿名类型,请更改第二个lambda,如下所示:
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: 如果您希望该值是您定义的类型,请更改第二个lambda,如下所示:
ToDictionary( t => t.Col1, t => new YourType { Prop1 = t.Col2 });
Since you just need value of one first row why not to do that first: 由于您只需要第一行的值,为什么不首先执行此操作:
var row = TheTable.FirstOrDefault();
And than just construct that dictionary if you got the result: 如果你得到了结果,那么只需构造那个字典:
return row == null ? null :
new Dictionary<string,string>{ {row.Column1, row.Column2 } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.