Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter linq list on property value

I have a List<int> and a List<customObject>. The customObject class has an ID property. How can I get a List<customObject> containing only the objects where the ID property is in the List<int> using LINQ?

Edit: I accepted Konrads answer because it is easier/more intuitive to read.

like image 843
Espo Avatar asked Sep 01 '08 11:09

Espo


People also ask

How to filter a list using LINQ?

The next example filters a list with LINQ's Where method. var vals = new List<int> {-1, -3, 0, 1, 3, 2, 9, -4}; List<int> filtered = vals. Where(x => x > 0). ToList(); Console.

How to use filter method in c#?

In this article Filtering refers to the operation of restricting the result set to contain only those elements that satisfy a specified condition. It is also known as selection. The following illustration shows the results of filtering a sequence of characters.


2 Answers

var result = from o in objList where intList.Contains(o.ID) select o
like image 104
Konrad Rudolph Avatar answered Oct 13 '22 22:10

Konrad Rudolph


using System.Linq;

objList.Where(x => intList.Contains(x.id));
like image 32
Robin Winslow Avatar answered Oct 13 '22 21:10

Robin Winslow