c# - 无法使用 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
任何帮助,将不胜感激!干杯!
解决方案
看起来你只想要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;
推荐阅读
- swift - Alamofire 处理特殊字符参数
- java - Java Jackson CSV:空标题字段
- python - 更改其中之一后更新模型对象
- laravel - laravel刀片内的Angular 6项目
- ios12 - 如果单个视图中有两个按钮,则无法通过 INUIAddVoiceShortcutButton 设置单独的 Siri 快捷短语
- matlab - 句柄和非句柄子类的抽象超类
- xamarin - 将轮播数据返回到对象中
- plot - 三角域上的等高线图
- node.js - 如何使用 pg.pool 在 koajs 的单个请求中从两个数据库中获取
- html - 将条件格式放入 HTMLBody