Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intersect two different .NET lists by a single property?

Tags:

c#

.net

I'm trying to filter my first list of Foo's based on some values in a second list of Baa's.

For example.

Here's an example I put up on .NET Fiddle ...

var foos = new List<Foo>
{
    new Foo { Name = "Leia" },
    new Foo { Name = "Han Solo" },
    new Foo { Name = "Chewbacca" },
    new Foo { Name = "Luke" },
};

    var baas = new List<Baa>
{
    new Baa { Alias = "aaaaa" },
    new Baa { Alias = "bbbb" },
    new Baa { Alias = "Leia" },
    new Baa { Alias = "Luke" }
};

// Expected output:
// List<Foo> results = Foo { "Leia" } and Foo { "Luke" };

See how I'm asking for: Filter the first list (by Name) by the second lists Alias property.

and that will return a List of Foo with 2 results in it?

Any clues?

like image 230
Pure.Krome Avatar asked Dec 07 '22 02:12

Pure.Krome


1 Answers

You can use Any on the list of baas:

foos.Where(f => baas.Any(b => b.Alias == f.Name));

Or use a join (cleaner in query syntax):

var query = 
    from f in foos
    join b in baas on f.Name equals b.Alias
    select f;

Here's the code in a full working .NET Fiddle.

like image 135
D Stanley Avatar answered Dec 08 '22 14:12

D Stanley