0

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?

Picture of Lists

2
  • To clarify... for every ListA[x] == 1, you want to get ListB[x]? Commented Mar 24, 2016 at 4:42
  • Yes, the best way to describe would be if I wanted to get the average of all the values in ListB WHERE ListA==1. Commented Mar 24, 2016 at 15:27

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.