0

I have a list inside a list, I need to convert it to list of string.

Below are the list properties.

List<UserOrganization> UserOrganizations { get; set; }

public interface UserOrganization
    {
       IEnumerable<UserRole> Roles { get; set; }
    }

public class UserRole
    {
        public int RoleId { get; set; }     
    }

I need to find all RoleId and return them in a list of string.

I tried below code but unable to get a list of string from it.

 var securityRoleIds= CallingUser.UserOrganizations.Select(x => x.Roles.Select(y=> y.RoleId).ToList()).ToList();
List<string> l2 = securityRoleIds.ConvertAll<string>(delegate(Int32 i) { return i.ToString(); });

Getting this error.

Cannot convert anonymous method to type 'Converter, string>' because the parameter types do not match the delegate parameter types

Sunil Bamal
  • 87
  • 1
  • 14

1 Answers1

3

Use SelectMany rather than Select:

List<string> list = CallingUser.UserOrganizations
    .SelectMany(x => x.Roles.Select(y => y.RoleId.ToString()))
    .ToList();

SelectMany flattens the nested collections.

Also, you can just use ToString() on each int in the collection, rather than converting them later.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35