linq中来自IQueryable过程的foreach [英] foreach from IQueryable procedure in linq
问题描述
大家好,我对linq有疑问:
我有一个课,进入我的课有一个可查询的IQueryable return
在过程中,有一个与linq的简单连接,我有一个 foreach .
hi everybody i have a problem with linq :
i have a class and into my class there is a precedure as IQueryable return
in procedure there is a simple join with linq and i have a foreach.
public static class Class1
{
public static IQueryable Testlinq()
{
var db = new DataClassesDataContext();
var query = from tit in db.titles
join autit in db.titleauthors
on tit.title_id equals autit.title_id
select new
{
tit.publisher,
tit.price,
autit.author
};
foreach (var item in query)
{
var tmp = item.author + " " + item.price + " " + item.publisher;
}
return query;
}
}
foreach完美地在这里.但是将此foreach副本复制到另一个文件以获取defaultl.aspx.cs无效:
foreach worked perfect here. but copy of this foreach to another file for examlpe default.aspx.cs doesn''t work:
var query = Class1.Testlinq();
foreach (var item in query)
{
var tmp = item.author + " " + item.price + " " + item.publisher;
}
作者,价格和发布者在这里未知.
这些物品在这里我该怎么知道?
在此先感谢
author and price and publisher are unknown here .
what must do i these items are known here?
thanks in advance
推荐答案
您不应从Testlinq
返回匿名类型
请在此页面上阅读我的答案:
我有问题在Linq to SQL返回查询?在方法中 [
You should not return anonymous types fromTestlinq
Please read my answer at this page :
I have a problem in Linq to SQL to return a query? in method[^]
And then make the helper class and returnIEnumerable<helperclassname></helperclassname>
from yourTestlinq()
method.
You will have access to theHelperClass
fields in yourforeach
body then.
Hope it helps.
你不能那样做.方法无法返回匿名类型.
创建具有作者,发布者和价格属性的类,然后从您的方法中返回它们.
这样,您的方法将返回已知类型,并且所有方法都将起作用.
定义类别:
Hi,
You can''t do that. Method can''t return anonymous type.
Create class with author, publisher and price properties and then return them from your method.
That way your method will return known type and all will work.
Define class:
public class YourClass
{
public string Publisher {get; set;}
public string Author {get; set;}
public int Price {get; set;}
}
并更改方法以选择并返回您定义的类型:
And change method to select and return your defined type:
public static class Class1
{
public static IQueryable<yourclass> Testlinq()
{
// ...
select new YourClass
{
Publisher = tit.publisher,
Price = tit.price,
Author = autit.author
};
foreach (var item in query)
{
var tmp = item.author + " " + item.price + " " + item.publisher;
}
return query;
}
}
也许有些语法错误,但是您会明白的...
Maybe there are some syntax errors but you will get the point...
尝试这段代码
try this code
var query = Class1.Testlinq();
foreach (var item in query)
{
item.author = item.author + " " + item.price + " " + item.publisher;
}
the item.author is replaced with this
(item.author + " " + item.price + " " + item.publisher;)
example output is
zyck 100.00 sample2012
这篇关于linq中来自IQueryable过程的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!