[英]c# How to get count of value in a List based on value in another List using LINQ
I understand how you can get the count of a List where each value might have some number. 我知道如何获取每个值可能都有一些数字的List的计数。 For example if I wanted the number of times a value was equal to 1 in "ListA" I would do the following: 例如,如果我想要“ ListA”中值等于1的次数,我将执行以下操作:
int countOf1=ListA.Count(x => x ==1);
If I have several Lists, and I want to get the count of ListB where ListA is equal to some value, how can I modify the above command to do so? 如果我有多个列表,并且我想获取ListA等于某个值的ListB的计数,如何修改上面的命令呢?
To illustrate the question, I will show a picture in a spreadsheet of what this would look like. 为了说明问题,我将在电子表格中显示其外观。 In the pic, you can see ListA and ListB will always have the same number of values, as I want information on each row to be an 'observation' of sorts. 在图片中,您可以看到ListA和ListB始终具有相同数量的值,因为我希望每行上的信息成为某种“观察”。
I could do this with a loop, but I would like my script to be a bit simpler. 我可以通过循环执行此操作,但是我希望自己的脚本更简单一些。 I also realize for this example, I could just get the count of ListA where the value is equal to 1. But I will have some other things I want to do in the future like compute averages, percentiles or other aggregations on ListB, where ListA is equal to some value. 我也意识到,在这个示例中,我可以获取值等于1的ListA的计数。但是我将来还会做其他一些事情,例如计算平均值,百分位数或ListB上的其他聚合,其中ListA等于某个值。
Is this possible to do? 这可能吗?
So it looks like what you want to do is join list A onto list B. You don't specify in your question how the two lists should be joined but based on your image I am guessing you want to do it by the index - ie A[0] to B[0], A[1] to B[1], etc. If that is the case you can use Zip
. 因此,看起来您想要执行的操作是将列表A连接到列表B。您没有在问题中指定如何将两个列表连接在一起,但是基于您的图像,我想您希望通过索引来执行-即A [0]至B [0],A [1]至B [1]等。如果是这种情况,则可以使用Zip
。 Then if you wanted to take the average of B where A equals 1, for example, you could do the following: 然后,例如,如果要取B等于A等于1的平均值,则可以执行以下操作:
ListA
.Zip(
ListB,
(a, b) => new { A = a, B = b })
.Where(x => x.A == 1)
.Average(x => x.B);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.