字典<string,string>到字典<control,object>使用IEnumerable <t> .Select()</t> </control,object> </string,string>

时间:2010-05-13 00:01:19

标签: c# linq dictionary lambda ienumerable

我有一个System.Collections.Generic.Dictionary<string, string>包含控件ID和数据绑定的相应数据列:

var dic = new Dictionary<string, string>
{
    { "Label1", "FooCount" },
    { "Label2", "BarCount" }
};

我这样使用它:

protected void FormView1_DataBound(object sender, EventArgs e)
{
    var row = ((DataRowView)FormView1.DataItem).Row;
    Dictionary<Control, object> newOne = dic.ToDictionary(
        k => FormView1.FindControl(k.Key)),
        k => row[k.Value]);
}

所以我正在使用IEnumerable<T>.ToDictionary(Func<T>, Func<T>)

是否可以使用IEnumerable<T>.Select(Func<T>)执行相同的操作?

1 个答案:

答案 0 :(得分:2)

当然,但返回值为IEnumerable<KeyValuePair<Control, object>>而不是Dictionary<Control, object>

IEnumerable<KeyValuePair<Control, object>> newOne = dic.Select(
    k => new KeyValuePair<Control, object>(FormView1.FindControl(k.Key), 
                                           row[k.Value]));

(未测试的)