2012-04-16 198 views
2

我是C#和Linq-to-Sql的新手。如何遍历linq-to-sql查询结果的结果并追加结果?

我有一个表这种形式的“InstrumentTypes”:

typeId(int) | type(varchar) | subttype(varchar) 

101    Keys   keyboard 
102    Keys   accessories 
103    Guitar   acoustic 
104    Guitar   electric 

我需要获取类型‘输入所有“从表基于由搜索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 
} 

我无法弄清楚如何遍历从查询的结果,将其存储在数据结构,并将其绑定到一个中继器。

下面的代码将其绑定到Repeater:

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(); 

但我得到一个编译错误说“的最佳重载的方法匹配列表有一些无效的参数'。我哪里错了?

+0

“迭代查询结果” - 为什么要循环遍历结果?什么样的数据结构? – SkonJeet 2012-04-16 07:47:28

+0

@SkonJeet:我已经更新了上面的问题。 – codewarrior 2012-04-16 08:30:56

回答

7

var type = (from m in database.InstrumentTypes 
     where m.type == requestType 
     select m); 

得到什么是InstrumentTypes的集合,而不是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); 
} 

,你可以很容易地转换为

var ids = (from m in database.InstrumentTypes 
     where m.type == requestType 
     select m.Id).ToList(); 

[编辑]

您可以直接查询您的仪器和导航到相关对象,只要您定义了InstrumentTypeInstrument之间的关系。

var instruments = (from i in database.Instrument 
         where i.InstrumentType.type == requestType 
         select i); 

不需要单独的foreach es或查询。 i.InstrumentType将转换为join,因为您可以使用SQL配置文件验证

+0

感谢您的回复!我已经更新了我的问题。你可以看一下吗? – codewarrior 2012-04-16 08:31:24

+1

太棒了,我不知道你可以直接做到这一点。非常感谢Arialdo! – codewarrior 2012-04-16 08:39:56

3

我不确定你在问什么。

没有明确定义查询的返回类型,您已经返回一个IEnumerable <InstrumentTypes>对象。如果你想要一个ID列表,你可以简化你的查询来返回ID而不是一个InstrumentType列表。当然,那么你会返回一个IEnumerable对象<int>。

var type = (from m in database.InstrumentTypes 
     where m.type == requestType 
     select m.typeId);