Reputation: 113
I understand how you can get the count of a List where each value might have some number. For example if I wanted the number of times a value was equal to 1 in "ListA" I would do the following:
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?
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.
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.
Is this possible to do?
Upvotes: 0
Views: 256
Reputation: 7029
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 - i.e. A[0] to B[0], A[1] to B[1], etc. If that is the case you can use Zip
. Then if you wanted to take the average of B where A equals 1, for example, you could do the following:
ListA
.Zip(
ListB,
(a, b) => new { A = a, B = b })
.Where(x => x.A == 1)
.Average(x => x.B);
Upvotes: 2