简体   繁体   English

合适的类型来存储Linq结果以便以后查询

[英]Suitable type to Store Linq result in order to be able to query it later

I'm using linq to sql in my project. 我在我的项目中使用linq to sql。 In Form1 I query a table like: Form1中,我查询如下表:

var dc = new Data.MyDataContext();
var query = from c in dc.Customers select c;  
program.MainForm.query = query;

Or in Form2 I query a table like: 或者在Form2中,我查询如下表:

var dc = new Data.MyDataContext();
var query = from b in dc.Banks select b;  
program.MainForm.query = query;

And I want to do something like the following later in MainForm : 我想稍后在MainForm中执行以下操作:

this.DataGridView1.DataSource = this.query.Where(item=>item.ID < 10);

I don't know how to store the object. 我不知道如何存储对象。 I tried storing it as an IQueryable but I was not able to query it because it is an Interface. 我尝试将其存储为IQueryable,但由于它是接口而无法对其进行查询。

I want to store results from different tables in query, what is the simple way to do so? 我想在查询中存储来自不同表的结果,这样做的简单方法是什么? I think Generics can help but I don't know how. 我认为泛型可以提供帮助,但我不知道如何。

If you want to hold on to the query you'll need a field of type IQueryable<T> with T being the type of object queried. 如果要继续查询,则需要IQueryable<T>类型的字段,其中T是要查询的对象的类型。

If you want to hold on to the result of the query (eg so you can search inside it in RAM without fetching the data again), you'll need some materialized data structure like IList<T> . 如果要保留查询结果(例如,这样就可以在RAM内进行搜索而无需再次获取数据),则需要一些具体的数据结构,例如IList<T>

Both options are problematic because they require type arguments, and UserControls can't be generic. 这两个选项都是有问题的,因为它们都需要类型参数,并且UserControls不能通用。 I guess you could work with IQueryable<object> and IList<object> but then you won't be able to do much with the resulting objects since the control will know nothing about their type. 我猜您可以使用IQueryable<object>IList<object>但是由于控件对它们的类​​型一无所知,因此您将无法对结果对象做很多事情。

As an aside, as @SergeyBerezovskiy noted, it's also probably not a great idea to mix data access and presentation logic like this. 顺便说一句,正如@SergeyBerezovskiy指出的那样,将数据访问和表示逻辑混合在一起并不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM