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

徘徊边缘 提交于 2021-02-04 18:29:25

问题


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?


回答1:


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.




回答2:


You could use Join:

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

Similar to this answer.



来源:https://stackoverflow.com/questions/23198032/how-can-i-intersect-two-different-net-lists-by-a-single-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!