简体   繁体   中英

Sql Query to Linq Query

I have written an sql qyery like

SELECT TOP 1000 
  [tlotWeight]
  ,[TEU]
  ,[SeaAirFlag]
  ,CASE 
  WHEN [SeaAirFlag]='SEA' OR [SeaAirFlag]='Sea' 
  then [TEU]  
  else [tlotWeight] end as Volume
FROM [LogisticsBI].[dbo].[GoldenVolume]

I want it to convert it to linq c# query,I have tried something like this

(from t in db.GoldenVolumes
 select new { Volume=(t.SeaAirFlag=="SEA"|| t.SeaAirFlag=="Sea")?t.TEU: t.tlotWeight)}
 ).Take(10000).Distinct()

but its showing some syntax error in linqpad Please help me to correct way in linq to write this query

Well, I see problem with brackets here (opened one time and closed two times):

select new { Volume = (t.SeaAirFlag=="SEA" || t.SeaAirFlag=="Sea") ? t.TEU : t.tlotWeight)}

It looks like this should be either

select new { Volume = ((t.SeaAirFlag=="SEA" || t.SeaAirFlag=="Sea") ? t.TEU: t.tlotWeight)}

or (it's up to you)

select new { Volume = (t.SeaAirFlag=="SEA" || t.SeaAirFlag=="Sea") ? t.TEU: t.tlotWeight }

The error is pretty straightforward you have misarranged your round brackets.

t.tlotWeight)}) is wrong instead it should be t.tlotWeight})

Its better to split them to next lines for more clearity.

    var res = (from t in db.GoldenVolumes
                   select new
                   {
                       Volume = (t.SeaAirFlag.ToUpperInvariant().Contains("SEA")) ?
                           t.TEU  : t.tlotWeight
                   })

                   .Take(10000)
                   .Distinct();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM