-1

I need to filter a list of objects according to whether a specific property (String type) contains the character 'S' (or 'N') in position 19.

I have this in C#:

IQueryable<Tabla5> lstTipoGasto = objServiceClient.ListaTabla5(int.Parse(number)).AsQueryable();
Tabla5 objTipoGasto = new Tabla5();
objTipoGasto.NombreNom5 = "Seleccione..";
objTipoGasto.CodigoNom5 = -1;
objTipoGasto.TextNom5 = "...";
List<Tabla5> lst = lstTipoGasto.ToList();
lst.Add(objTipoGasto);
lstTipoGasto = lst.AsQueryable();

var lista = lstTipoGasto.AsEnumerable().ToList().Where(x => x.AgregaTabl.Contains("S"))
    .Select(x => new 
    { 
        x.CodigoNom5, 
        x.NombreNom5, 
        x.TextNom5, 
        x.AgregaTabl 
    }).OrderBy(x => x.CodigoNom5).ToList();

uddlTipoGasto.DataSource = lista;            
uddlTipoGasto.DisplayMember = "NombreNom5";
uddlTipoGasto.ValueMember = "CodigoNom5";
uddlTipoGasto.ValueMember = "TextNom5";  

I get an exception. Any ideas why?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 3
    What is the exception message? Also your code doesn't check the character at position 19 right now. – Rahul Singh Aug 03 '15 at 14:34
  • It doesn't seem like you're checking position 19, you're just using `Contains()`.. – haim770 Aug 03 '15 at 14:36
  • The exception is (in spanish): Referencia a objeto no establecida como instancia de un objeto. – Rafael Giraldo Aug 03 '15 at 14:39
  • The original query: `var lista = lstTipoGasto.AsEnumerable().ToList().Where(x => x.AgregaTabl.Substring(18, 1).Equals("S")).Select(x => new { x.CodigoNom5, x.NombreNom5, x.TextNom5, x.AgregaTabl }).OrderBy(x => x.CodigoNom5).ToList();` – Rafael Giraldo Aug 03 '15 at 14:42

1 Answers1

0

Try...

var lista = lstTipoGasto.AsEnumerable()
    .ToList()
    .Where(x => x.AgregaTabl.Length > 18 && 
           (x.AgregaTabl[18] == 'S' || x.AgregaTabl[18] == 'N'))
    .Select(x => new 
    { 
        x.CodigoNom5, 
        x.NombreNom5, 
        x.TextNom5, 
        x.AgregaTabl 
    }).OrderBy(x => x.CodigoNom5).ToList();

Instead of checking if x.AgregaTabl.Contains("S"), you check that x.AgregaTabl.Length > 18 so we know that it has at least 19 characters, then we check (x.AgregaTabl[18] == 'S' || x.AgregaTabl[18] == 'N') to see if the 19th character is 'S' or 'N' (Note: x.AgregaTabl[18] accesses the 19th character due to 0-based indices).

Shar1er80
  • 9,001
  • 2
  • 20
  • 29