如何<myobject>从具有逗号分隔 ID 的数据源创建<字符串、列表>元组



我有这个对象

 [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; }
 }

每个用户都有一个模块,所以一个用户可以有多个模块。

所以我需要知道如何创建这个元组与模块列表:

 Tuple<string, List<Modulo>> modulosPorUsuarioDeDirectorioActivo;

不要太担心下面代码的技术细节,我只是有一个带有模式扩展(自定义属性)的azure活动目录,该模式扩展以这种格式为一个用户保存模块: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));
 }

但是我不知道如何在foreach中创建Tuple对象

在程序上,您将创建一个List<Modulo>并通过为每个id添加Modulo实例将其填充到for循环中,然后在循环后创建元组。

但是一个更简单的方法(嗯,更少的输入)可能是使用LINQ;Select方法可以将每个id投影到Modulo实例中:

// 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);

在c#中,您创建Tuples的方式与创建任何对象的方式相同。

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

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

最新更新