Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何计算两个独立的linq条件_C#_Linq - Fatal编程技术网

C# 如何计算两个独立的linq条件

C# 如何计算两个独立的linq条件,c#,linq,C#,Linq,让我们假设有一个XML文件,其中包含并希望计数 -出生日期在2000年之前的人和 -出生日期在2000年之前的人和M地区的人 我可以得到如下计数 <person> <name>Mehmet</name> <date>25.07.1974</date> <region>M</region> 执行上述命令的速度很快。 但是有相同的压缩,我觉得不好。 我不计算ToList和ToArray,但我认为上面的代码更快。 我

让我们假设有一个XML文件,其中包含并希望计数 -出生日期在2000年之前的人和 -出生日期在2000年之前的人和M地区的人

我可以得到如下计数

<person>
<name>Mehmet</name>
<date>25.07.1974</date>
<region>M</region>
执行上述命令的速度很快。 但是有相同的压缩,我觉得不好。 我不计算ToList和ToArray,但我认为上面的代码更快。 我正在寻找更快的替代解决方案,如果可能的话。
感谢您的回答

您可以计算x中有多少项的区域等于M

int x = List.Where( x=> x.Date < dateTime2000 ).Count();

int y = List.Where( x=> x.date < dateTime2000 && x.region == "M" ).Count();
另外,我想知道为什么这么多人喜欢使用列表而不是数组

你可以用这个:

 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

这将只循环第一次查询的结果,而不是所有元素。

那么,您至少可以对两个计数重复使用第一次查询:

var prior2000 = List.Where(x => x.Date < dateTime2000).ToList();
var x = prior2000.Count;
var y = prior2000.Count(x => x.region == "M");
另一种使用类似于字典的查找的方法:

var birthPrio2000 = List.Where( x=> x.Date < dateTime2000 ).ToList();
int countBirthPrio2000 = birthPrio2000.Count;
int countBirthPrio2000RegionM = birthPrio2000.Count(x => x.region == "M");

如果确实要确保源代码只迭代一次,则可以使用.Aggregate函数并自行执行逻辑:

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

因为您必须至少对整个集合进行一次数据整理,所以调用Enumerable.Count而不是ToList.Count并没有真正的区别。因此,真正的问题不是什么时候打电话给ToList,而是什么时候。所有答案都是正确的。但根据我的说法,这是一个更合适的列表。其中x=>x.Dater.Region.Selectg=>g.Count;
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;