Home > Back-end >  Get muiltiple items from list (two or more non consecutive)
Get muiltiple items from list (two or more non consecutive)

Time:11-13

I searched the web for this very simple question but I didn´t find a simple answer.

Tried next lines with error but I´d like to know if there is a simplest way.

List<string> listaStr = new List<string> {"cero","uno","dos","tres","cuatro"};
List<int> indices = new List<int> {0,4};
var valores = new List<object>();

foreach (var i in indices)
{
valores.Add(listaStr[i]);
}

foreach (var i in valores)
{
Console.WriteLine(valores[i]);
}

Expecting as output: "cero","cuatro" in a new list (valores)

CodePudding user response:

I tried the following code and it seems to work:

    List<string> listaStr = new List<string> {"cero","uno","dos","tres","cuatro"};
    List<int> indices = new List<int> {0,4};
    var selectedStrings = new List<object>();
    
    foreach(var index in indices)
    {
        selectedStrings.Add(listaStr[index]);
    }
    
    foreach(var value in selectedStrings)
    {
        Console.WriteLine(value);
    }

Make sure you have all the required imports set above:

using System;
using System.Collections.Generic;

If the error still persists I will come back and try to answer again.

I've edited the code, please have a look.

CodePudding user response:

This should do the trick. Last loop is just to display the items in the resulting list.

var listaStr = new List<string> { "cero", "uno", "dos", "tres", "cuatro" };
var indices = new List<int> { 0, 4 };
var selectedStrings = new List<string>();

foreach (var i in indices)
{
    selectedStrings.Add(listaStr[i]);
}

foreach (var s in selectedStrings)
{
    Console.WriteLine(s);
}

CodePudding user response:

As an alternative the result can be obtained by using a LINQ expression. This is harder to read and probably a bit slower when using a lot of strings however.

var listaStr = new List<string> { "cero", "uno", "dos", "tres", "cuatro" };
var indices = new List<int> { 0, 4 };

var selectedStrings = listaStr.Where(x => indices.Contains(listaStr.IndexOf(x))).ToList();

foreach (var s in selectedStrings)
{
    Console.WriteLine(s);
}
  • Related