繁体   English   中英

如何迭代linq-to-sql查询结果的结果并附加结果?

[英]How to iterate over results of a linq-to-sql query result and append the results?

我是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 Repeater。

到目前为止,我已经编写了以下代码:

// 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。

以下代码将其绑定到Repeater:

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

有人可以帮帮我吗?

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

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

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

你得到了什么

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或查询。 i.InstrumentType将转换为join ,您可以使用SQL事件探查器进行验证

我不确定你在问什么。

在显式定义查询的返回类型时,您已经返回了IEnumerable <InstrumentTypes>对象。 如果你想要一个ID列表,你可以简单地优化你的查询以返回ID而不是一个InstrumentTypes列表。 当然,那么你将返回一个IEnumerable <int>对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM