[英]how to count two seperate where condition linq
<person>
<name>Mehmet</name>
<date>25.07.1974</date>
<region>M</region>
假設有一個XML文件,其中包含要計數的文件
-出生日期在2000年之前的人,以及
-出生日期在2000年之前和M區的人
我可以得到如下計數。
int x = List.Where( x=> x.Date < dateTime2000 ).Count();
int y = List.Where( x=> x.date < dateTime2000 && x.region == "M" ).Count();
以上的執行速度很快。
但是有同樣的誇獎,我覺得那還不行。
我不計算ToList()和ToArray(),但我認為上述代碼更快。
如果可能,我正在尋找更快的替代解決方案。 謝謝答案
您可以使用此:
var prior2000 = List.Where(x => x.Date < dateTime2000).ToList();
var x = prior2000.Count;
var y = prior2000.Count(x => x.region == "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我想知道為什么這么多人喜歡使用列表而不是數組。
好吧,您至少可以將第一個查詢重用於兩個計數:
var birthPrio2000 = List.Where( x=> x.Date < dateTime2000 ).ToList();
int countBirthPrio2000 = birthPrio2000.Count;
int countBirthPrio2000RegionM = birthPrio2000.Count(x => x.region == "M");
使用查找的另一種方法(類似於字典):
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();
如果您確實想確保僅對源進行一次迭代,則可以使用.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.