[英]How to get a List<anonymous type> generated by Linq outside of an using statement?
Got a query using the using statement, which means once it ends the object created gets disposed.使用 using 语句进行查询,这意味着一旦它结束,创建的 object 就会被释放。
using (Context context = new())
{
var records = context.PoRecords
.Join(
context.PoStatuses,
record => record.PoStatus,
status => status.Id,
(record, status) => new
{
record.PoNumber,
record.PrNumber,
Status = status.Name,
}
).ToList();
}
How can I get that list outside of that using?我怎样才能在使用之外获得该列表? What I think I have to do is create a custom class for that query, declare a list of that type outside the using and fill it with the contents of the query, I've done that when I query the whole table, but, since this is joining tables I can't just declare
List<CustomType> records =...querywithjoins...
because the list Linq is returning is of an anonymous type.我认为我要做的是为该查询创建一个自定义 class ,在 using 之外声明该类型的列表并用查询的内容填充它,当我查询整个表时我已经这样做了,但是,因为这是加入表我不能只声明
List<CustomType> records =...querywithjoins...
因为 Linq 返回的列表是匿名类型。 I'd have to do that outside the using, kind of like this:我必须在使用之外这样做,有点像这样:
List<CustomType> records;
using (Context context = new()){
records = TheWholeQuery.ToList();
}
Another way I thought of doing it was, since I am listing the results of the query in a list view with a foreach, creating new objects of the custom type and add them into the new list, but, that means I'd have to iterate through each and every query I do, and I don't intend to do that everytime.我想到的另一种方法是,因为我在带有 foreach 的列表视图中列出查询结果,创建自定义类型的新对象并将它们添加到新列表中,但是,这意味着我必须遍历我所做的每一个查询,我不打算每次都这样做。
Is there a way to do this?有没有办法做到这一点? Or a workaround??
还是解决办法??
You could use a tuple if you don't want to define a class although I have found in these circumstances it's usually ends up being easier to just define the class.如果您不想定义 class,则可以使用元组,尽管我发现在这些情况下通常更容易定义 class。
List<Tuple<int, int, string>> records = null;
using (Context context = new())
{
records = context.PoRecords
.Join(
context.PoStatuses,
record => record.PoStatus,
status => status.Id,
(record, status) => new Tuple<int, int, string>(
record.PoNumber,
record.PrNumber,
status.Name
)
).ToList();
}
If u don't want to remove using statement u can just convert your list with anonymous type to list of 'CustomType'如果您不想删除 using 语句,您可以将匿名类型的列表转换为“CustomType”列表
so..所以..
List<CustomType> records;
using (Context context = new())
{
records = context.PoRecords
.Join(
context.PoStatuses,
record => record.PoStatus,
status => status.Id,
(record, status) => new CustomType()
{
PoNumber = record.PoNumber,
PrNumber = record.PrNumber,
Status = status.Name,
}
).ToList();
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.