Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq getting a list from another list

Tags:

c#

join

linq

I have two collections: one is Items And Another is ActiveItems

The only intersection between these two collection is Name

I want a list with Linq from Items where the Items names are in the ActiveItems with that name

I wrote this code is there a better idea:

Items.Where(i => ActiveItems.Count(v=> v.Name==i.Name) > 0)
like image 210
Navid Rahmani Avatar asked Jun 12 '11 18:06

Navid Rahmani


2 Answers

I would probably create a set of the names from ActiveItems and then use that:

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 join, e.g. with a query expression:

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

Note that this will give duplicate item values if there are multiple ActiveItem values with the same name. Another alternative join, which doesn't have this problem but is a bit clumsier:

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

Note that all of these will avoid the O(N * M) check for names - they'll all use hash tables behind the scenes, to give an O(N + M) complexity.

like image 50
Jon Skeet Avatar answered Nov 19 '22 10:11

Jon Skeet


Items.where(i => ActiveItems.Any(a => i.Name == a.Name))
like image 34
Magnus Avatar answered Nov 19 '22 09:11

Magnus