Home > Software engineering >  C# linq how to get all the first elements of a nested dynamic list?
C# linq how to get all the first elements of a nested dynamic list?

Time:02-04

I have a nested list List<list<dynamic>>, I'd like to get all the first elements of the second level and form a new List<dynamic>.

I know .first() gets the first element of a list, but how can I give multiple elements from multiple sub list?

Thanks in advance.

CodePudding user response:

try this please if you want to take the first two elements of each list, and the more elements you want you can increase the integer in the .Take().

List<List<string>> originalList = new List<List<string>>()
{
    new List<string>(){"1","1","1"},
    new List<string>(){"2","2"},    
};    

    var FirtTwoElementsList = originalList.Select(x => x.Take(2)).ToList();
    List<string> FinalList = new List<string>();
    foreach (var item in FirtTwoElementsList)
    {
       FinalList.AddRange(item.ToList<string>());
    }

CodePudding user response:

Proper and efficient way of doing this is as follows:

mainList.Select(subList => subList?.First()).OfType<dynamic>();

This will take care of null lists and null elements

If you want to select all the elements of sublists try following

mainlist.Select(subList => subList).OfType<List<dynamic>>();

This will only take care of null lists

CodePudding user response:

You can try as below -

mainList.Where(subList => subList != null && subList.Count > 0).Select(subList => subList.First()).ToList();
  •  Tags:  
  • Related