【问题标题】:How to iterate over results of a linq-to-sql query result and append the results?如何迭代 linq-to-sql 查询结果的结果并附加结果?
【发布时间】:2012-04-16 07:42:16
【问题描述】:

我是 C# 和 Linq-to-Sql 的新手。

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

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
}

我无法弄清楚如何迭代查询的结果,将它们存储在数据结构中并将它们绑定到中继器。

以下代码将其绑定到Repeater:

Repeater1.DataSource= //name of data structure used to store the types goes here
Repeater1.DataBind();

谁能帮帮我?

编辑: 对于获得的每个 typeID,我想访问另一个表“仪器”并检索属于该 typeId 的所有仪器。 表“仪器”是这样的:

instrumentId     typeID    name     description
1000             101       yamaha   xyz

根据 Arialdo 的回答,我正在这样做:

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

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

【问题讨论】:

  • "遍历查询结果" - 为什么要循环遍历结果?什么样的数据结构?
  • @SkonJeet:我已经更新了我上面的问题。

标签: c# asp.net sql-server linq linq-to-sql


【解决方案1】:

你从中得到什么

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

无需单独的foreaches 或查询。 i.InstrumentType 将转换为 join,您可以使用 SQL 分析器进行验证

【讨论】:

  • 感谢您的回复!我已经更新了我的问题。你能看一下吗?
  • 太棒了,我不知道你可以直接这样做。非常感谢阿里尔多!
【解决方案2】:

我不确定你在问什么。

如果没有明确定义查询的返回类型,您已经返回了一个 IEnumerable 对象。如果您想要一个 ID 列表,您可以简单地优化您的查询以返回 ID 而不是 InstrumentTypes 列表。当然,那么您将返回一个 IEnumerable 对象。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多