C# 如何迭代linq to sql查询结果并附加结果?
我对C和Linq都是新手 我有一个表格“InstrumentTypes”,如下表所示:C# 如何迭代linq to sql查询结果并附加结果?,c#,asp.net,sql-server,linq,linq-to-sql,C#,Asp.net,Sql Server,Linq,Linq To Sql,我对C和Linq都是新手 我有一个表格“InstrumentTypes”,如下表所示: typeId(int) | type(varchar) | subttype(varchar) 101 Keys keyboard 102 Keys accessories 103 Guitar acoustic 104 Guitar
typeId(int) | type(varchar) | subttype(varchar)
101 Keys keyboard
102 Keys accessories
103 Guitar acoustic
104 Guitar electric
我需要根据“type”作为输入的搜索从表中获取所有的“typeId”,并且所有的typeId都需要绑定到ASP中继器
到目前为止,我已经编写了以下代码:
// requestType contains the type from the search
var type = (from m in database.InstrumentTypes
where m.type == requestType
select m);
foreach(var typeId in type)
{
//code
}
我不知道如何迭代查询结果,将它们存储在数据结构中,并将它们绑定到一个转发器 以下代码将其绑定到中继器:
Repeater1.DataSource= //name of data structure used to store the types goes here
Repeater1.DataBind();
谁能帮我一下吗
编辑:
对于获得的每个typeID,我希望访问另一个表“Instruments”,并检索属于该typeID的所有仪器。
“仪器”表如下所示:
instrumentId typeID name description
1000 101 yamaha xyz
根据阿丽亚尔多的回答,我正在这样做:
var type = (from m in database.InstrumentTypes
where m.type == requestType
select m);
var instruments = new List<Instrument>();
foreach (var i in type)
{
instruments.Add(from x in database.Instruments
where x.typeId == i.typeId
select x);
}
Repeater1.DataSource = instruments;
Repeater1.DataBind();
但是我得到一个编译错误,说“列表的最佳重载方法匹配有一些无效参数”。我哪里出错了?你从中得到了什么
var type = (from m in database.InstrumentTypes
where m.type == requestType
select m);
是InstrumentType的集合,而不是ID的集合
这对我有用
var types = (from m in database.InstrumentTypes
where m.type == requestType
select m);
var ids = new List<int>();
foreach (var type in types)
{
ids.Add(type.Id);
}
[编辑]
只要定义了InstrumentType和Instrument之间的关系,就可以直接查询仪器并导航到相关对象
不需要有单独的foreach或查询。i.InstrumentType将转换为联接,您可以使用SQL探查器验证这一点。我不确定您在问什么 如果没有显式定义查询的返回类型,则已经返回了IEnumerable对象。如果您想要一个ID列表,您可以简单地优化查询以返回ID,而不是一个类型列表。当然,那么您将返回一个IEnumerable对象
迭代查询结果-为什么要循环查询结果?什么样的数据结构?@SkonJeet:我已经更新了上面的问题。谢谢你的回答!我已经更新了我的问题。你能看一下吗?太棒了,我不知道你能直接做到。非常感谢阿里亚尔多!
var ids = (from m in database.InstrumentTypes
where m.type == requestType
select m.Id).ToList();
var instruments = (from i in database.Instrument
where i.InstrumentType.type == requestType
select i);
var type = (from m in database.InstrumentTypes
where m.type == requestType
select m.typeId);