简体   繁体   中英

Write lambda statement to select items from a list where a property of an item (enum) is found in a list of enum values?

I have a cache where I store Project objects. One property of a project is it's ProjectState , which can be Active, Inactive, Canceled, or Archived.

I would like to give the user an option to select a given number of project states, and then pull all of the projects that have a state in that list. For example, the list could have all four states:

List<ProjectState> states = new List<ProjectState>() 
{ 
   ProjectState.Active, 
   ProjectState.Inactive, 
   ProjectState.Canceled,
   ProjectState.Archived
};

Unfortunately, I find myself writing a condition for each and every state:

List<Project> myProjects = myCache.Where(p => 
   p.state == ProjectState.Active || 
   p.state == ProjectState.Inactive || 
   p.state == ProjectState.Canceled || 
   p.state == ProjectState.Archived).ToList();

Is there any way I can condense this statement to check if an item is in the list? While this is invalid syntax, I would like something that could do:

var myProjects = myCache.Where(p => p.state IN states).ToList();

I have found the solution, and I will answer this question to share it because I am sure I am not the first or last person to come across this type of scenario. However, is there a better solution? Is there syntax out there to check if 'an item is in a list' as opposed to 'if a list contains an item'?

After racking my brain for a while and digging through documentation, I realized my logic was wrong.

I was too focused on selecting projects where the state was in the list, that I wanted to find syntax that matched that train of thought. However, I realized I could use the Contains() function because it is the same for me to select projects where the list contains the state of that project.

The solution to my problem was:

var myProjects = myCache.Where(p => states.Contains(p.state)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM