0

Say I have the following List<List<string>>:

List<List<string>> input=new List<List<string>>();

for (int i = 0; i < 6; i++)
{
    input.Add(new List<string>());
}

input[0]=new List<string>{"David","3","Ceviche"};
input[1]=new List<string>{"Corina","10","Beef Burrito"};
input[2]=new List<string>{"David","3","Fried Chicken"};
input[3]=new List<string>{"Carla","5","Water"};
input[4]=new List<string>{"Carla","5","Ceviche"};
input[5]=new List<string>{"Rous","3","Ceviche"};

How would I find the total count of distinct strings at input[i][1]? So in this case the count is 3 because you have "3","5","10"

What I have gives me 4

int count=input.SelectMany(x => x[1]).Distinct().Count();

1
  • 3
    Just use Select instead of SelectMany. What you're doing is counting the distinct characters of the strings at position 1, which are 3, 1, 0 and 5. It does that because string is a IEnumerable<char>. Commented Aug 18, 2021 at 1:42

1 Answer 1

2

Skip 1, Take 1.

int count=input.SelectMany(x => x.Skip(1).Take(1)).Distinct().Count();

SelectMany wants an IEnumerable, which is what Take returns. Note that this is uhm, more forgiving, than using an index, i.e. if the list doesn’t have the correct number of elements it doesn’t throw an exception. As long as that isn’t a problem for you (either not encountered or what you want, that should work just fine.

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.