Linq gets a list from another list

I have two collections: one is the elements and the other is ActiveItems

The only intersection between the two collections is Name

I need a list with Linq from elements where element names are in ActiveItems with that name

I wrote this code, there is a better idea:

Items.Where(i => ActiveItems.Count(v=> v.Name==i.Name) > 0)
+5
source share
4 answers

I would probably create a set of names from ActiveItemsand then use this:

var activeNames = new HashSet<string>(activeItems.Select(x => x.Name));
var itemsWithActiveNames = items.Where(x => activeNames.Contains(x.Name))
                                .ToList();

Another option is to use a connection, for example. with query expression:

var query = from activeItem in activeItems
            join item in items on activeItem.Name equals item.Name
            select item;

, item, ActiveItem . , , :

var query = from item in items
            join activeItem in activeItems 
                on item.Name equals activeItem.Name
                into g
            where g.Any()
            select item;

: O (N * M) - - , O (N + M).

+11
Items.where(i => ActiveItems.Any(a => i.Name == a.Name))
+4
var results = from i1 in collection1.Items
              join i2 in collection2.ActiveItems on i1.Name equals i2.Name
              select i2.Name;
0
source

Connection Usage:

from item in Items
join active in ActiveItems on item.Name equals active.Name
select item
0
source

All Articles