I want to filter an IEnumerable object by a specific property of whatever object it is collecting. I want the option to filter by one or more property value but how many values (and what values) to filter by is only known at runtime.
Ok, so to give an example, the collected objects could be the following struct:
public struct Person { public string Name { get; set; } public string Profession{ get; set; } } This struct could then be used by the following list, which I have populated with some arbitrary values:
List<Person> people= new List<Person>; people.Add(new Person(){Name = "Mickey", Profession="Tinker"}; people.Add(new Person(){Name = "Donald", Profession="Tailor"}; people.Add(new Person(){Name = "Goofy", Profession="Soldier"}; people.Add(new Person(){Name = "Pluto", Profession="Spy"}; This is then put into an IEnumerable (all of them are transferred to it first)
var wantedPeople = from n in this.people select n; So say a user was only interested in the "Tailor" and "Spy" professions, and via some sort of gui trickery the following collection was created:
List<string> wantedProfessions = new List<string>(); wantedProfessions.Add("Tailor"); wantedProfessions.Add("Spy"); Now what Linq statement can I use to filer my wantedPeople so it only includes the tailor and spy entries? I know I could use a where clause but I don't know how to tailor it to get what I want (and doing the following is not what I want as it only works with the wantedProfessions collection above (e.g. this collection will change at runtime):
wantedPeople = from n in wantedPeople where n.Profession == wantedProffessions[0] || n.Profession == wantedProffessions[1] select n;