[英]Linq Get count from multiple where condition
I want something really simple, i want from a list of records to find the ones of a specific date (records can have the same date more than once) and with a specific value,我想要一些非常简单的东西,我想从记录列表中找到特定日期的记录(记录可以多次具有相同的日期)并且具有特定的值,
and count how many of those values exist.并计算这些值中有多少存在。 So far i'm using this but im not sure if it is the best approach
到目前为止,我正在使用这个,但我不确定这是否是最好的方法
Here is Records这里是记录
public class Records
{
public DateTime Date { get; set; }
public int Record { get; set; }
}
and here is the code这是代码
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()});
}
I want to know the sum of the appearance of a specific Date and a specific value in Record So if the database has these values:我想知道记录中特定日期的外观和特定值的总和所以如果数据库有这些值:
11/11/1980, 3 11/11/1980, 3
11/11/1980, 3 11/11/1980, 3
12/11/1980, 2 12/11/1980, 2
I want to get as a result 2 when i will seek for the count of the conditions 11/11/1980 and 3我想在寻找条件 11/11/1980 和 3 时得到结果 2
var result = records.GroupBy(x => x.Date)
.Select(x => new { Date = x.Key, Count = x.Count() });
is what you want是你想要的
result will now have a list of dates and count.结果现在将有一个日期和计数列表。
if you want a specific value then like this:如果你想要一个特定的值,那么像这样:
var result = records.Where(x => x.Record == -1).
.GroupBy(x => x.Date)
.Select(x => new { Date = x.Key, Count = x.Count() });
To group by the date and not the date time use the date property of the object in the GroupBy statement要按日期而不是日期时间分组,请在 GroupBy 语句中使用对象的日期属性
.GroupBy(x => x.Date.Date)
What you want is a couting of all dates.您想要的是所有日期的计数。 GroupBy() allows you to distinctly select all dates.
GroupBy() 允许您明确选择所有日期。 Then you can Count() all grouped records with some conditions as you want.
然后,您可以根据需要对具有某些条件的所有分组记录进行 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
So given a DateTime date and an int recordValue, you want to count all Records from your recordCollection that have a property Date equal to date and a property Record equal to RecordValue.因此,给定一个 DateTime 日期和一个 int recordValue,您希望计算 recordCollection 中具有等于 date 的属性 Date 和等于 RecordValue 的属性 Record 的所有记录。
How about this:这个怎么样:
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.