Selecting an Item from a List<T> with index equal to the iteration value of for

Asked

Viewed 915 times

4

How can I select an item from a list by the index, this being equal to the iteration value of a for?

I tried to accomplish using LINQ, while compiling and inspecting the StringBuilder which would store the item, I get only the name of the using concatenated with the project name and the class.

StringBuilder dados = new StringBuilder(); //Cria StringBuilder
int Contador = (from q in Lista select q.Codigo).Count();  
....

///método que gera string
...
for (int i = quantidade * 10; i < (quantidade * 10) + 10; i++)
{
  if (i >= Contador)
  {
    break;
  }      
  var cod = Lista.Where(c => c.Codigo == i.ToString()).Select(c=>c.Codigo);

  dados.AppendLine(Convert.ToString(cod));
}

Result of inspection of StringBuilder:

System.Linq.Enumerable+Whereselectlistiterator`2[projectinho. Pedido+Item,System.String]

Why does this happen? How to solve?

  • 1

    Missing chunks of code, for example where the variable is Contador. It would be nice to know also how this list is, although you can already see at least one error. What do you call storing the item? The question is not clear exactly as the string should be mounted.

  • Hello Maniero, The Counter variable receives the amount of items in the List. This is a list of an object. Storing the item would be to take the Product Code, stored in the variable cod and add to StringBuilder

2 answers

2


I can almost guarantee that it can be improved, but the question does not give information that help in this, so what I can do is indicate the punctual solution and improve what gave to me to see:

var dados = new StringBuilder();
int contador = (from q in lista select q.Codigo).Count(); //queria eliminar isto, não parece fazer sentido
for (int i = quantidade * 10; i < (quantidade * 10) + 10 && i < contador; i++) dados.AppendLine((lista.Single(c => c.Codigo == i.ToString())).Codigo);

I put in the Github for future reference.

The method Single() returns an item as the Where returns a list of items, having an item, just grab the field you want from it.

  • Thank you for the reply Manieiro... I noticed that I failed to explain a very important detail :( In this case, the index of the Code would have to be equal to the iteration of the for. That way, it would only be added to StringBuilder the code of index 0, when the i of the iteration also for 0...

  • And that’s what you’re doing, actually I didn’t even touch it. What might be happening is that you don’t have one of them and then the SingleOrDefault() might be more appropriate, and then logic would have wanted to be slightly different, but in fact I said the question was not so clear, but you did not clarify.

  • I made the proposed change, now by going through the list I’m getting the following exception System.InvalidOperationException: 'A sequência não contém elementos de correspondência', from what I understand this occurs because there is no index corresponding to iteration?

  • That’s what I said in the comment above.

  • Thanks for the help @Maniero. This response gave me a good direction. After a while bumping my head I discovered the operations Skip() and Take() where I skip items according to the iteration of for and take the next 10.

1

It’s kind of hard to know what you want to do (and then think about how). What’s the expected result? It would be a String with 10 object codes from the list between Qtd*10 and Qtd*10+10?

In this case it could be done with just a query:

No[] lista = { new No("7"), new No("16"), new No("18"), new No("19"), new No("20"), new No("21")};
int quantidade = 1;
int start = quantidade * 10;
int end = start + 10;
String[] codigos = lista
              .Where(no => Convert.ToInt32(no.Codigo) >= start &&  Convert.ToInt32(no.Codigo) < end)
              .Select(no => no.Codigo).ToArray();
String saida = String.Join(", ", codigos);

See the example working here: https://dotnetfiddle.net/sfy7Jk

Browser other questions tagged

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