簡體   English   中英

linq 為 C# 應用程序選擇不同和計數

[英]linq with select distinct and count for the C# application

我有兩個 sql 查詢,我已經測試過兩個查詢都在工作。 我需要轉換為下拉列表的 Linq 查詢(MVC C#)。 有什么方法可以讓 Linq 查詢只顯示日期而不顯示時間? 例如僅日期 2015-09-30

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

輸出

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

我的第二個查詢,我只需要轉換 linq 列表

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

根據您問題中的SQL ,等效的Linq將是

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();

這個

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

和這個

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

對於僅獲取日期的第一個查詢,您可以在選擇時截斷時間.Date將僅獲取日期並刪除時間部分。

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

對於第二個查詢

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM