2012-04-16 197 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);