简体   繁体   中英

best way to use LINQ to query against a list

i have a collection

IEnumerable<Project>

and i want to do a filter based on project's Id property to included any id that is in a list:

List<int> Ids

what is the best way to do a where clause to check if a property is contained in a list.

var filteredProjectCollection = projectCollection.Where(p => Ids.Contains(p.id));

You may be able to get a more efficient implementation using the Except method:

var specialProjects = Ids.Select(id => new Project(id));
var filtered = projects.Except(specialProjects, comparer); 

The tricky thing is that Except works with two collections of the same type - so you want to have two collections of projects. You can get that by creating new "dummy" projects and using comparer that compares projects just based on the ID.

Alternatively, you could use Except just on collections of IDs, but then you may need to lookup projects by the ID, which makes this approach less appealing.

var nonExcludedProjects = from p in allprojects where Ids.Contains(p => p.Id) select p;

If you're going to use one of the .Where(p=> list.Contains(p)) answers, you should consier first making a HashSet out of the list so that it doesn't have to do an O(n) search each time. This cuts running time from O(mn) to O(m+n).

I'm not sure that I understand your question but I'll have a shot.

If you have: IEnumerable enumerable, and you want to filter it such that it only contians items that are also present in the list: List list, then: IEnumerable final = enumerable.Where(e => list.Contains(e));

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