user2164172
user2164172

Reputation: 37

How to match a column which has multiple integer values separated by commas in linq?

I have list, in which i have column with multiple integer values(separated by commas).

eg:
------------------------
| Program | Module      |
------------------------
| I       | 1,2,3       |
------------------------
| II      | 2, 3        |
------------------------
| III     | 1,3         |
------------------------

Now, supppose, if i want to select programs where module is 2.

 int sid = 2; 
 IEnumerable<int> ids = Program.All.FindAll( item => 
     sid.contains(
         item.Module.Split(',').Select(s => (int)s)
     )
 )

getting compilation error:

cannot convert string to int

Can any one plz help me.

Thanks

Upvotes: 0

Views: 358

Answers (2)

Ciro Corvino
Ciro Corvino

Reputation: 2128

considers that Program IDs are roman numbers, therefore you should provide a custom conversion for get them in int.. my solution get an IEnumerable of string

 string sid = "2"; 
 IEnumerable<string> ProgramIds = 
   Program
  .Where( prg => 
     (("#") + prg.Module + "#").Contains("#"+sid+"#") 
    ||
     (("#") + prg.Module + "#").Contains("#"+sid+",") 
    ||
     (("#") + prg.Module + "#").Contains(","+sid+",") 
     )
  ).Select(prg => prg.Program)

for roman number conversion try these links they are both all good solutions...

https://stackoverflow.com/a/26667855/3762855

https://stackoverflow.com/a/27976977/3762855

Upvotes: 0

Save
Save

Reputation: 1423

You can convert your sid to string only once and search it like a string

var sidAsStr = sid.ToString();
var result = Program.All.FindAll(item => item.Module.Split(',')
    .Any(s => s.Trim() == sidAsStr));

Maybe it is more productive solution because it avoids many parse operations

Upvotes: 1

Related Questions