如何在c#中的public scope中声明var数据类型?

时间:2015-06-22 04:34:11

标签: c# linq

我用linq写简单查询到sql:

var query = (from p in behzad.GAPERTitles
                         select new
                         {
                             p.id,
                             p.gaptitle
                         }).ToArray();


将代码放入c#windows应用程序,windows窗体加载事件,我想将结果用于此范围内的按钮单击事件:

private void button1_Click(object sender, EventArgs e)
        {
              //using var query array in this scope for example string temp=query[i].id
        }


我该如何解决?

1 个答案:

答案 0 :(得分:4)

将其声明为已知类型(不是匿名类型),例如:

Dictionary<int, string> results = new Dictionary<int, string>();

然后您可以将结果存储在词典中:

results = behzad.GAPERTitles.ToDictionary(x => x.id, x => x.gaptitle);

稍后再提及:

private void button1_Click(object sender, EventArgs e)
{
    // use results in this scope, for example: string title = results[someId]
}

如果结果的顺序很重要,那么词典就不会起作用。您可以使用元组或仅为此场合创建一个类:

List<Tuple<int, string>> results = new List<Tuple<int, string>>();

...
results = behzad.GAPERTitles.Select(x => Tuple.Create(x.One, x.Two)).ToList();

...
// use results, for example:
//    string id = results[i].Item1; string title = results[i].Item2;