Abstract class to access elements from an object collection

Asked

Viewed 85 times

1

I’m doing my first project on C#, I’m creating data from a multi-object JSON file that contains basic information from a file (Filename, Datacreation, Size).

Filing cabinet jsonArquivos.json:

[  {
   "NomeDoArquivo" : "PrimeiroArquivo",
   "DataCriacao" : "10/10/2020",
   "Tamanho" : 200
}, {
   "NomeDoArquivo" : "TerceiroArquivo",
   "DataCriacao" : "09/09/2020",
   "Tamanho" : 250
}, {
   "NomeDoArquivo" : "SegundoArquivo",
   "DataCriacao" : "08/08/2020",
   "Tamanho" : 150
}  ]

Class Arquivo.cs:

public class Arquivo {
  public String NomeDoArquivo { get; set; }
  public String DataCriacao{ get; set; }
  public int Tamanho{ get; set; }
}

My intention is to use a sequence of 10,000 objects in a collection to apply a sorting algorithm with the selected property. To do this, I would like to create a method that receives the selected property and go through all the elements to copy into an array and reorder them. Something like:

public void copiaArray(string propriedade, object obj){
   var[] vetorCopia = new var[arquivos.Count]; 
   // Não sei se posso fazer isso de ainda, talvez eu tenha que realizar uma versão para string[] e uma para int[].
   for(i=0; i<arquivos.Count; i++){
      vetorCopia[i] = arquivos[i].propriedade; 
   // Sei que posso acessar um objeto da collection por índice, mas não sei como acessar a propriedade a seguir do índice sem ter que especificar diretamente no código e ter que criar um método pra cada propriedade.
   }
} 

My doubts are:

I can access the property by index too (arquivos[i].[proprieade]) or I’m forced to wear a foreach and somehow compare the past property?

I’m in the best way to get an array copy of a specific collection property?

Note: I came from Java, I’m still studying the terms C#, feel free to correct me, I’m still very shallow. Note 2: I appreciate the attention so far, and I realized that I need to clarify some things. The sort I mentioned earlier will be variable according to the algorithm specified later (bubbleSort, Selectionsort, Quicksort...) The type of data I am getting after deserialize json for the collection of objects in my Typeof is System.Collections.Generic.List`1 which I intend to traverse by index, but it has its own list of properties.

[System.Collections.Generic.List][index].NomeDoArquivo;
[System.Collections.Generic.List][index].DataCriacao;
[System.Collections.Generic.List][index].Propriedade;

My intention was to pass this collection by parameter to go through each object index, and also generalize the access to property (maybe by index too) to access directly according to a parameter definition.

static String[] transformaParaVetor(System.Collections.Generic.List, int Propriedade){
   for(i=0; i < [System.Collections.Generic.List].Count; i++){  
      str[i] = [System.Collections.Generic.List][index].[indexPropriedade]
   }
   return str;
}

1 answer

0


If you are looking to sort a list I recommend using Enublerable.Orderby

Example (https://docs.microsoft.com/pt-br/dotnet/api/system.linq.enumerable.orderby?view=netcore-3.1):

minhaLista.OrderBy(x => x.Tamanho); //ou
minhaLista.OrderBy(x => x.DataCriacao); // ou

But if you want to access the properties dynamically, there are two ways to implement your idea

1. You can use indexers in classes.

It would be something like

public int this[int index]
{
    // get and set accessors
}

Follow the Microsoft link for how to implement https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/indexers/using-indexers

2. Reflection

Something like:

public void metodo(string propriedade, object obj)
{
    object valorDaPropriedade = obj.GetType().GetProperty(propriedade).GetValue(obj);
    // ...
}

Follow the Microsoft link https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/concepts/reflection

  • Thank you, I was unaware of the reflection, and it will be very useful to me even to finalize the desired method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.