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)
LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions.
To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.
Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.
LINQ is based on C# which is a declarative language, means whenever you want to use any variable name, it must have been already been declared beforehand. In LINQ queries, when you write "From" first - it declares the variable whoch can later be used in "Select" statement.
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;
You can try this.
List firstnames = names.Split(';').ToList();
var query = from c in customers
where firstnames.Contains(c.FirstName)
select c ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With