Select String attribute using Split and LINQ?

Asked

Viewed 38 times

1

I have the following string "1,2,3,4,5,6,7,8,9,10," that I want to make a Split in a Select to search in the database if the number 9 is inserted in a field that receives strings of numbers. I want to do this using C# LINQ without having to use foreach or something similar.

How to do this ?

I’m trying like this

public class SequenciaNumero {
     public string Numeros {get;set;}
}

SequenciaNumero sn = new SequenciaNumero();
sn.Numeros = "1,2,3,4,";

SequenciaNumero sn1 = new SequenciaNumero();
sn1.Numeros = "5,6,7,8,9,10,"

context.SequenciasNumeros.Add(sn, sn1);
context.SaveChanges();

//pesquisar numeros a partir de uma string de numeros
string _pesquisaNumeros = "10,11,12,15,"

//teste de split no LINQ
context.SequenciasNumeros
       .Select(x => x.Numeros.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries))
       .Where(x => _pesquisaNumeros.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries)
       .Any(y => y.Equals(x)));

//erro
Exception thrown: 'System.NotSupportedException' in EntityFramework.dll

In my test, I’m trying to search from a string of numbers by searching the numbers that exist in common in the string database. In this case, return only the number 10 that should be found _pesquisaNumeros

  • 2

    which version of the Entity Framework? and also which database?

  • @novic EF 6.4 and Mysql

  • then it won’t work because it can’t translate it to SQL, what you can do is in memory, but then there’s the cost of performance... I don’t know if it’s worth it

1 answer

-1

Solved.

var _myNum = context.SequenciasNumeros
                                    .AsEnumerable()
                                    .SelectMany(x => x.Numeros.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                                    .Intersect(_pesquisaNumeros.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                                    .ToArray();

Browser other questions tagged

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