6

I have a string with semi-comma separated names:

string names = "Jane;Harry";

I also have a list of customer objects:

public class Customer
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

List<Customer> customers = new List<Customer>();
customers.Add(new Customer(){FirstName="John", LastName="Doe"});
customers.Add(new Customer(){FirstName="Jane", LastName="Doe"});
customers.Add(new Customer(){FirstName="Harry", LastName="Potter"});

var query = from c in customers
            select c;

How do I create a query that returns only those customers that has a first name that is in the semi-comma separated list?

Something like the T-SQL SELECT FistName FROM customer WHERE FirstName IN (list) (sort of)

dove
  • 20,075
  • 14
  • 85
  • 106
Magnus Johansson
  • 27,443
  • 19
  • 102
  • 161

3 Answers3

15

Well, you should really split the string up to start with - otherwise you'll get a match for "Jane" even if the list is "Janet;Harry".

You could do:

string[] validNames = names.Split(';');
var query = customers.Where(c => validNames.Contains(c.FirstName));

Another option is to use a HashSet, which will perform a lot better when the list is very large:

HashSet<string> validNames = new HashSet<string>(names.Split(';'));
var query = customers.Where(c => validNames.Contains(c.FirstName));

I've used dot notation here instead of a query expression because it's simpler when you're just applying a clause or two. As a query expression though, it would be:

var query = from c in customers
            where validNames.Contains(c.FirstName)
            select c;
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1

You can try this.

List firstnames = names.Split(';').ToList();

var query = from c in customers
            where firstnames.Contains(c.FirstName) 
            select c ;    
Suraj Kumar
  • 5,366
  • 8
  • 19
  • 39
dove
  • 20,075
  • 14
  • 85
  • 106
-1

It Will Helps

string allid = "11,12,13,14,15,16";
string[] arrid = allid.Split(',');
var data = context.MyModels.Where(x => arrid.Contains(x.ProjectId.ToString()));
Suraj Kumar
  • 5,366
  • 8
  • 19
  • 39
rinku Choudhary
  • 865
  • 1
  • 8
  • 18