How can I cross two different .NET lists with one property?

I am trying to filter my first Foo list based on some values ​​in the second Baa list.

For instance.

Here is an example that I installed 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 ask: filter the first list (through Name) using the second list of properties Alias.

and it will return a list Foowith two results in it?

Any clues?

+4
source share
2 answers

You can use Anyin the list baas:

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

Or use a connection (cleaner in the query syntax):

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

Here is the code in a full working .NET script.

+9

Join:

var results = foos.Join(baas, f => f.Name, b => b.Alias, (f, b) => f);

.

+5

Source: https://habr.com/ru/post/1537374/


All Articles