0

Can anyone help how to use the associated search using linq ("where in" in sql)?

Linq Where search follows here,

1. select * from tablename where code = 'code1'
`string[] numbers = { "one", "two", "three", "four" };

string searchNumber = "two";
var number = from number1 in numbers
                     where number1 == searchNumber
                     select number1;

foreach (var n in number)
    Console.WriteLine(n);

        Console.ReadLine();`

How to search the set of codes using LINQ?

2. select * from tablename where code in ('code1','code2')
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
user1531248
  • 521
  • 1
  • 5
  • 17

5 Answers5

2

For first answer use this

var result = tablename.Where(x => x.code == "code1");

For second answer use this

List<string> str = new List<string>(){ "code1" , "code2" };

var result = tablename.Where(x => str.Contains(x.code));
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

Try something along the lines of..

string[] codes = { "code1", "code2" };
var selections = tablename.Where(x => codes.Contains(x.code));
Carson63000
  • 4,215
  • 2
  • 24
  • 38
0
string[] searchNumber = {"two","one"};
        var number = from number1 in numbers
                     where searchNumbers.Contains(number1)
                     select number1;

        foreach (var n in number)
        {
            Console.WriteLine(n);
        }

        Console.ReadLine();

That should do the trick.

KyorCode
  • 1,477
  • 1
  • 22
  • 32
0

It depends on what you're going against. If you're using Entity Framework then you're going to need to look up creating an In statement. If you're just using Linq against an IEnumerable, contains will do what you want.

The reason being that if you're executing this against a database, the provider has to have implemented the Contains. Entity Framework doesn't IIRC.

tbddeveloper
  • 2,407
  • 1
  • 23
  • 39
0

You need to invert the way you're thinking about this. Ask if numbers.Contains(searchNumber). Something like:

var result = from n in numbers
                 where numbers.Contains(searchNumber)
                 select n;
Alvaro Rodriguez
  • 2,820
  • 2
  • 33
  • 38