Luis Valencia
Luis Valencia

Reputation: 34008

How to create a tuple of <string, List<myobject>> from datasource with comma delimited IDs

I have this object

 [Serializable]
 public class Modulo
 {
     [Key]
     // ReSharper disable once UnusedAutoPropertyAccessor.Global
     public int Id { get; set; }
     public string Nombre { get; set; }
     public string ClaseFontAwesome { get; set; }
 }

Modulos are per user, so One user can have many modules.

SO I need to know how to create this tuple with the list of modulos:

 Tuple<string, List<Modulo>> modulosPorUsuarioDeDirectorioActivo;

Dont worry too much about the technical details of the code below, I just have an azure active directory with a schema extension (custom property), that schema extension saves the modules for one user in this format: 1,2,5,7

 var extPropLookupNameModulos = $"extension_{SettingsHelper.ClientId.Replace("-", "")}_{"Modulos"}";
 var client = AuthenticationHelper.GetActiveDirectoryClient();
 var user = await client.Users.GetByObjectId(identityname).ExecuteAsync();
 var userFetcher = (User)user;
 var unitOfWork = new UnitOfWork();

 var keyvaluepairModulos = userFetcher
      .GetExtendedProperties()
      .FirstOrDefault(prop => prop.Key == extPropLookupNameModulos);

 var idsModulos = keyvaluepairModulos.Value.ToString().Split(',');
 foreach (var idModulo in idsModulos)
 {
     var modulo = 
         unitOfWork.ModuloRepository.GetById(Convert.ToInt32(idModulo));
 }

But I dont know how to create the Tuple object inside the foreach.

Upvotes: 0

Views: 382

Answers (2)

vgru
vgru

Reputation: 51244

Procedurally, you would create a List<Modulo> and fill it inside the for loop by adding Modulo instances for each id, and then create the tuple after the loop.

But a simpler way (well, less typing anyway) might be to use LINQ; Select method can project each id into a Modulo instance:

// split the string into an array of int ids
var idsModulos = keyvaluepairModulos.Value.ToString().Split(',');

// project each id into a modulo instance
var listOfModulos = idsModulos
    .Select(id => unitOfWork.ModuloRepository.GetById(Convert.ToInt32(id)))
    .ToList();

// it's simpler to use Tuple.Create instead of the Tuple constructor
// because you don't need to specify generic arguments in that case (they are infered)
var tuple = Tuple.Create(name, listOfModulos);

Upvotes: 2

tdbeckett
tdbeckett

Reputation: 708

In c#, you create Tuples the same way you create any object.

   var tuple = new Tuple<string, List<Modulo>>("string", new List<Modulo>());

https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

Upvotes: 2

Related Questions