Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c# - Usinq Linq to select items that is in a semi-comma separated string?

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...