【问题标题】:Convert sql query to linq in C#在 C# 中将 sql 查询转换为 linq
【发布时间】:2017-11-25 07:31:01
【问题描述】:

嗨,任何人都可以帮助如何在 Linq C# 中编写以下查询

select YearValue from [Information].Year 
where YearId in (select max(YearId) from curreny where BudgetCodeId = 2)

这是我尝试过的:

var maxYear = 
    from year in dbContext.Years 
    join exchange in dbContext.CurrencyExchangeRates 
    on year.YearId equals exchange.YearId 
    where exchange.BudgetCodeId == budgetCodeId 
    orderby year.YearValue descending 
    select new { yearValue = year.YearValue };

【问题讨论】:

  • 到目前为止你尝试过什么? SO 不是代码编写服务。
  • 我试过这样但没有得到想要的输出。 var maxYear = from year in dbContext.Years join exchange in dbContext.CurrencyExchangeRates on year.YearId 等于 exchange.YearId 其中 exchange.BudgetCodeId == budgetCodeId orderby year.YearValue 降序选择新 { yearValue = year.YearValue };
  • 这看起来与您所追求的 SQL 完全不同。 CurrencyExchangeRates 是什么?为什么按年份排序?
  • 我想要年份表中的年份值,其中 yearId 取自 currencyexchangeRate 表,并且年份 id 应该是最大值
  • 您是否听说过或尝试过使用 LinqPad。我发现它对这样的事情非常有用。

标签: c# sql linq-to-entities


【解决方案1】:

这就是你要找的东西:

var maxYear = from year in dbContext.Years where (from exchange in dbContext.CurrencyExchangeRates where exchange.BudgetCodeId == 2 select exchange)
    .Max(m => m.YearId) == 
        year.YearId select year.YearValue;

int mYear = maxYear.First();

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 2020-12-13
    • 2021-05-30
    • 1970-01-01
    • 2019-02-22
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多