簡體   English   中英

Linq 從多個 where 條件中獲取計數

[英]Linq Get count from multiple where condition

我想要一些非常簡單的東西,我想從記錄列表中找到特定日期的記錄(記錄可以多次具有相同的日期)並且具有特定的值,

並計算這些值中有多少存在。 到目前為止,我正在使用這個,但我不確定這是否是最好的方法

這里是記錄

    public class Records
    {
        public DateTime Date { get; set; }
        public int Record { get; set; }

    }

這是代碼

 List<Records> records = GetRecords();
 var distinctDates = records.Select(x => x.Date).Distinct().ToList();


 for (int i = 0; i < distinctDates.Count(); i++)
 { 
     statistics.Rows.Add(new object[] { distinctDates[i].ToString("MM/dd/yyyy HH:mm"),
     records.Select(x => x).Where(d => d.Date == distinctDates[i]).Count(x => x.Record == -1).ToString()});
 }

我想知道記錄中特定日期的外觀和特定值的總和所以如果數據庫有這些值:

11/11/1980, 3

11/11/1980, 3

12/11/1980, 2

我想在尋找條件 11/11/1980 和 3 時得到結果 2

var result = records.GroupBy(x => x.Date)
                    .Select(x => new { Date = x.Key, Count = x.Count() });

是你想要的

結果現在將有一個日期和計數列表。

如果你想要一個特定的值,那么像這樣:

var result = records.Where(x => x.Record == -1).
                    .GroupBy(x => x.Date)
                    .Select(x => new { Date = x.Key, Count = x.Count() });

要按日期而不是日期時間分組,請在 GroupBy 語句中使用對象的日期屬性

                    .GroupBy(x => x.Date.Date)

您想要的是所有日期的計數。 GroupBy() 允許您明確選擇所有日期。 然后,您可以根據需要對具有某些條件的所有分組記錄進行 Count() 計數。

records.GroupBy(x => x.Date).Select(x => new
{
    Date = x.Key,
    Count = x.Count(y => y.Record == -1)
}) // This should give you all distinct dates with count

因此,給定一個 DateTime 日期和一個 int recordValue,您希望計算 recordCollection 中具有等於 date 的屬性 Date 和等於 RecordValue 的屬性 Record 的所有記錄。

這個怎么樣:

Datetime date = new DateTime(1980, 11, 11);
int recordValue = 3;
var result = recordCollection

    // keep only the records with date and recordValue:
    .Where(record => record.Date == date && record.Record == recordValue)

    // and Count them:
    .Count();

暫無
暫無

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

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