首页 > 解决方案 > 无法使用 LINQ 分组进行转换

问题描述

嗨,这就是我到目前为止所拥有的......在我的控制器中:

public ActionResult SingleFeed (string linename)
{
    var result = (from x in db.is1
                  where x.in_service == "Y"
                  join y in db.isckts on
                  x.is_id equals y.is_id
                  where y.line_name == linename
                  group new {x, y} by x.is_id into xyg
                  where xyg.Count() == 1
                  select xyg);
    var SFM = new CircuitsViewModel()
    {
        IsDetails = result.ToList()
    };

    return View(SFM);
}

在我看来:

public class CircuitsViewModel
{
        public List<is1> IsDetails { get; set; }
        public List<isckt> IscktDetails { get; set; }
}

我最终得到一个

不能将类型 'System.Collections.Generic.List(System.Linq.IGrouping(short, (anonymous type: is1 x, isckt y)))' 隐式转换为 'System.Collections.Generic.List(is1)

想知道是否有人可以帮助解决此错误。当我尝试使用 LINQ 分组时开始发生,但我不知道如何为 Viewmodel 建模或更改 LINQ 查询以匹配类型。

LINQ 查询背后的想法是返回在表 isckts 的 id 列中没有重复条目的记录。

更新:目前试图弄清楚如何在 db.isckts.is_ID 中查找重复项,然后在 IS_ID 上进行连接,然后在哪里指定 line_name 和 in_service

任何帮助,将不胜感激!干杯!

标签: c#asp.net-mvclinq

解决方案


看起来你只想要db.is1那些没有重复db.isckts匹配行的行,所以你只需要分组并返回这些is1行。

var result = from x in db.is1
             where x.in_service == "Y"
             join y in db.isckts on x.is_id equals y.is_id
             where y.line_name == linename
             group x by x.is_id into xg
             where xg.Count() == 1
             select xg.First();

但是,由于您只是使用分组来计算连接的行,因此您可以使用 LINQ Group Join 运算符来执行此操作:

var AjoinB = from x in db.tableA
             where x.inservice
             join y in db.tableB on x.is_id equals y.is_id into yj
             where yj.Count(y => y.line_name == linename) == 1
             select x;

我切换到 lambda 语法以将条件添加到 count on y; 您也可以将条件添加到db.tableB使用该Where方法,甚至创建一个子查询来表示过滤后的db.tableB

var filtered_isckts = from y in db.isckts
                      where y.line_name == linename
                      select y;
var result = from x in db.is1
             where x.in_service == "Y"
             join y in filtered_isckts on x.is_id equals y.is_id into yj
             where yj.Count() == 1
             select x;

要将 s 修改filtered_isckts为仅包含id一行,请在第一个查询中执行 group by:

var filtered_isckts = from y in db.isckts
                      where y.line_name == linename
                      group y by y.is_id into yg
                      where yg.Count() == 1
                      select yg.First();
var result = from x in db.is1
             where x.in_service == "Y"
             join y in filtered_isckts on x.is_id equals y.is_id
             select x;

推荐阅读