Usinq Linq选择半逗号分隔字符串中的项目?

时间:2009-10-08 10:24:38

标签: c# .net linq

我有一个半逗号分隔名称的字符串:

string names = "Jane;Harry";

我还有一个客户对象列表:

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;

如何创建一个只返回名字在半逗号分隔列表中的客户的查询?

像T-SQL SELECT FistName FROM customer WHERE FirstName IN (list)之类的东西 (某种程度上)

3 个答案:

答案 0 :(得分:13)

好吧,你应该把字符串分开来开始 - 否则即使列表是“珍妮特;哈利”,你也会获得“简”的匹配。

你可以这样做:

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

另一种选择是使用HashSet,当列表非常大时,它会表现得更好:

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

我在这里使用了点符号而不是查询表达式,因为当你只应用一个或两个子句时它更简单。但作为查询表达式,它将是:

var query = from c in customers
            where validNames.Contains(c.FirstName)
            select c;

答案 1 :(得分:1)

List<string> firstnames = names.Split(';').ToList();

            var query = from c in customers
                        where firstnames.Contains(c.FirstName) 
                        select c ;

答案 2 :(得分:0)

会有所帮助

string allid =“ 11,12,13,14,15,16”;

string [] arrid = allid.Split(',');

var data = context.MyModels.Where(x => arrid.Contains(x.ProjectId.ToString()));