Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from a List<T>

I'm sure there's an wasy way of doing this (I'm guessing one of the extension methods?), but am struggling to find it with Google.

Basically I have a List of custom classes; I want to select some items from this into a new List where one of the properties is equal to any value in another List.

Here's a (simplified) quick example of what I'm trying to do:

public class Job
    {
        public int Number;
        public string ClientCompanyName;            
    }

List<Job> lstJobs = new List<Job>();
List<Job> lstCompare = new List<Job>();

normally I would do something like:

List<Job> lstFiltered = new List<Job>();
foreach(Job jobThis in lstCompare)
{
    foreach(jobComp in lstCompare)
    {
        if(jobThis.Number = jobComp.Number)
        {
            lstFiltered.Add(jobThis);
        }
    }
}

Is there an extension method that neatens this last bit up into (ideally) a single line?

Cheers

like image 623
Jez Clark Avatar asked Dec 05 '25 16:12

Jez Clark


1 Answers

You can use Intersect() for this:

http://msdn.microsoft.com/en-us/library/bb460136.aspx

like image 156
C.Evenhuis Avatar answered Dec 08 '25 08:12

C.Evenhuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!