Gaya3
Gaya3

Reputation: 167

Get a count list of a nested list using LINQ

I have a nested list which looks like this:

List<List<int>> nestedList = new List<List<int>>();

Sample data be like: {{1,2,3}, {4,4,2,6,3}, {1}}

So I want to count each list and get the value to another list. For an example, the output should be : {3,5,1}

I have tried that using a foreach:

List<int> listCount = new List<int>();
foreach (List<int> list in nestedList)
{
    listCount.Add(list.Count());
} 

Can I know how to get this output using LINQ?

Thank you!

Upvotes: 5

Views: 786

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

This should work:

var result = nestedList.Select(l => l.Count).ToList();

Upvotes: 12

Related Questions