我用linq to 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
}
我该如何解决?
将其声明为已知类型(不是匿名类型),例如:
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;