c# - how to select columns from two table with where using linq
问题描述
I have three tables:
service_group
{
id,
title
}
service
{
id,
title,
group_id
}
service_rate
{
id,
title,
service_id,
price,
date
}
I have a combobox for group_service
and user must select one and then open a form and user could have a choice from service_rate
list.
service_rate
list includes all servic_rate
with service_id
in service.id
which selected service_group_id
.
Excuse me if I don't speak English well.
My code:
var list = (
from p in db.Tbl_Services
where p.Service_Group_ID == _service_group_id
select new {
p.ID,
p.Title,
p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().Price,
p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().date
}).ToList();
but doesn't seem to work.
解决方案
You can do something like this:
var list = db.Tbl_Services_Rate
.Where(x=>x.service.group_id == _service_group_id && x.service_id != null && x.service_id != "")
.GroupBy(x=>x.service_id)
.Select(x=>x.OrderByDescending(y=>y.id).FirstOrDefault())
.ToList();
Null check is because you will remove those records that may contain service_id as null or empty since you will have to check by using this id.
推荐阅读
- reactjs - 如何在 Jhipster+ React 应用程序中自定义 GUI
- objective-c - 如何从终端设置 macOS 编码语言 - Flutter
- java - n = n--; 为什么和以前一样的价值
- r - R ComplexUpset 包中的内存管理
- asp.net - 不使用 SPA (React) 启动 ASP.net 服务
- asp.net - 在 WCF 服务应用程序中使用 Google 登录
- vtk - 如何在 python-vtk 中隐藏特定的演员
- apache-kafka - 一段时间后,Apache Kafka 服务器自动停止
- unit-testing - Kotlin 中的单元测试和高阶函数
- excel - Excel:如何使用前几个字符查找部分匹配项