我有一个包含“abc”、“def”等值的IEnumerable。
我试图形成一个linq查询,其中我的对象中的属性值可能等于我的ienumerable中包含的许多值之一。如何形成linq查询?

var statesFilter = new List<string>();
statesFilter.Add("NY");
statesFilter.Add("CA");

var employees = new List<Employee>();
employees = getDataFromSomewhere();

// Code below is not working. Just wanted to give you an idea about my LINQ query
var myFilteredList = employees.Where(x => x.State.Contains(statesFilter));

员工班可能是这样的:
public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string State { get; set; }
}

最佳答案

如果State属性是string类型,则应将Where更改为以下类型:

var myFilteredList = employees.Where(x => statesFilter.Contains(x.State));

此外,您还可以执行以下操作:
var myFilteredList = employees.Where(x => statesFilter.Any(s=>s==x.State));

关于c# - 确保值等于LINQ中的多个值之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35004450/

10-09 07:32