简体   繁体   中英

linq with select distinct and count for the C# application

I have two sql query, I have already tested both queries are working. What I need to convert to Linq query for the dropdown list(MVC C#). Are there any way to Linq query should display only date without time? Eg only date 2015-09-30

  SELECT DISTINCT DelDate  from Location where    
  DStatus = 'true' and FState = 'true' 

output

2015-09-30 14:06:37.000
2015-09-30 14:14:09.547

My second query, I need to convert linq list only

SELECT COUNT(DISTINCT CouName) AS StatusCount  FROM Location  where   
DlStatus = 'true' and FState = 'true'  and CouName = 'Alan'

As per the SQL in your question, equivalent Linq will be

SELECT DISTINCT DelDate from Location where DStatus = 'true' and FState = 'true'

var delDates = Location
  .Where(l => l.DStatus == "true" && l.FState == "true")
  .Select(f => f.DelDate)
  .Distinct();

SELECT COUNT(DISTINCT CouName) AS StatusCount FROM Location where DlStatus = 'true' and FState = 'true' and CouName = 'Alan'

var statusCount = Location
  .Where(l => l.DStatus == "true" && l.FState == "true" && l.CouName == "Alan")
  .Select(f => f.CouName)
  .Distinct()
  .Count();

This

db.Location.Where(x=>x.DStatus == "true" && x.FState == "true")
           .Select(y=>y.DelDate.Value.ToString("yyyy-MM-dd")).Distinct().ToList();

and this

    db.Location.Where(x=>x.DStatus == "true" && x.FState == "true" && x.CouName == "Alan")
               .Select(y=>y.CouName).Distinct().Count();

for first query to get only date you can truncate time at selection .Date will get only Date and remove Time portion.

var dates = Location.Where(l => l.DStatus && l.FState)
                    .Select(f => f.DelDate.Date)
                    .Distinct();

for second query

var count = Location.Where(l => l.DStatus && l.FState && l.CouName == "Alan")
                    .Select(f => f.CouName)
                    .Distinct()
                    .Count();

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