[英]how to count two seperate where condition linq
<person>
<name>Mehmet</name>
<date>25.07.1974</date>
<region>M</region>
Let's assume there is a XML file which contains and want to count 假设有一个XML文件,其中包含要计数的文件
- persons who's birthdate is prior 2000 and -出生日期在2000年之前的人,以及
- person who's birthdate is prior 2000 and region M -出生日期在2000年之前和M区的人
I can get counts as below. 我可以得到如下计数。
int x = List.Where( x=> x.Date < dateTime2000 ).Count();
int y = List.Where( x=> x.date < dateTime2000 && x.region == "M" ).Count();
Executions of aboves are fast. 以上的执行速度很快。
But there are same comprasions and i feel it is not OK. 但是有同样的夸奖,我觉得那还不行。
I do not calculate ToList() and ToArray() ,but i think above codes are more faster. 我不计算ToList()和ToArray(),但我认为上述代码更快。
I am looking for faster alternative solution,if possible. 如果可能,我正在寻找更快的替代解决方案。 Thanks for answers
谢谢答案
You could use this: 您可以使用此:
var prior2000 = List.Where(x => x.Date < dateTime2000).ToList();
var x = prior2000.Count;
var y = prior2000.Count(x => x.region == "M");
This will only loop the results of the first query instead of all elements. 这只会循环第一个查询的结果,而不是所有元素。
You can count how many items in x have region equal to "M" 您可以计算x中有多少个项目的区域等于“ M”
var itemsBefore2000 = List.Where( x=> x.Date < dateTime2000 ).ToArray();
int x = itemsBefore2000.Length;
int y = itemsBefore2000.Where( x=> x.region == "M" ).ToArray().Length;
// or
itemsBefore2000.Count( x=> x.region == "M" ); // this one is preferable
PS I wonder why so many people like to use Lists instead of arrays. PS我想知道为什么这么多人喜欢使用列表而不是数组。
Well, you could at least reuse the first query for both counts: 好吧,您至少可以将第一个查询重用于两个计数:
var birthPrio2000 = List.Where( x=> x.Date < dateTime2000 ).ToList();
int countBirthPrio2000 = birthPrio2000.Count;
int countBirthPrio2000RegionM = birthPrio2000.Count(x => x.region == "M");
Another approach that uses a lookup (similar to a dictionary): 使用查找的另一种方法(类似于字典):
var birthPrio2000Regions = List.Where(x => x.Date < dateTime2000).ToLookup(x => x.Region);
int prio2000_TotalCount = birthPrio2000Regions.Sum(g => g.Count());
int prio2000_RegionM_Count = birthPrio2000Regions["M"].Count();
If you really want to ensure that the source is iterated only once you can use the .Aggregate()
function and do the logic on yourself: 如果您确实想确保仅对源进行一次迭代,则可以使用
.Aggregate()
函数并对自己进行逻辑处理:
var desiredValues = persons.Aggregate(
new { All = 0, InRegion = 0 },
(sum, person) => new
{
All = person.Date < dateTime2000 ? sum.All + 1 : sum.All,
InRegion = person.Region == "M" ? sum.InRegion + 1 : sum.InRegion
});
var prio2000_TotalCount = desiredValues.All;
var prio2000_RegionM_Count = desiredValues.InRegion;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.