【问题标题】:Selecting multiple from LINQ query从 LINQ 查询中选择多个
【发布时间】:2015-04-15 12:47:47
【问题描述】:

我使用这段小代码来获取我需要的 ID,并将它们放入一个数组中

var userids = from a in db.Person
              select a.idlist;

string[] idarray = userids.FirstOrDefault().ToString().Split(';');

如何使用这个 id 数组来选择另一个查询中的匹配行,像这样

[HttpGet]
public ActionResult GetStuff()
{
    var Item = from a in db.Table
               where a.id == idarray[0]
               and where a.id == idarray[1]
               and where a.id == idarray[2]
               etc...
               select new
                   {
                       a.itemid,
                       a.Element
                   };

    return Json(Item, JsonRequestBehavior.AllowGet);
}

【问题讨论】:

  • this 对您有帮助吗?

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 model-view-controller


【解决方案1】:

试试这样的:

var Item = from a in db.Table
           where idarray.Contains(a.id)
           select new
               {
                   a.itemid,
                   a.Element
               };

【讨论】:

    【解决方案2】:
    var Item = from a in db.Table
               where idarray.Contains(a.id)
               select new
                   {
                       a.itemid,
                       a.Element
                   }.ToArray();
    

    【讨论】:

      【解决方案3】:

      您不想使用Extension Method Lambda 语法吗?我是同一个 Linq,但只是有更多类似代码的视图:

      var Item = db.Table.Where(x => x.Contains(a.id))
                 .Select(x => new
                     {
                         a.itemid,
                         a.Element
                     }).ToArray();
      

      【讨论】:

        【解决方案4】:

        这是我通常做的。

        获取您需要的 ID:

        var ids = something.Where(s => s.SomeCondition).Select(s => s.Id);
        

        现在让我们根据 ID 获取数据:

        var response = anothertable.Where(a => ids.Contains(a.Id);
        

        然后,您可以将其设为列表、数组或任何您想要对其进行的操作。它将遍历anothertable 中的所有记录,并找到a.Id 匹配任何ids 的记录。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-21
          • 2023-04-09
          • 1970-01-01
          • 1970-01-01
          • 2020-11-05
          相关资源
          最近更新 更多