nekitip
nekitip

Reputation: 365

find elements of different types in two lists with common property value, linq variant of two for each loops

there are two lists

  1. Myobjects list contains all items, all have property "oid" of ObjectID
  2. The list of ObjectID types is list of ALL objects to be
    deleted

Problem is to find any item in Myobjects that has ObjectID in oid property. I'm having a hard time finding equivalent of this two "for each" loops in LINQ. This should be easy, but I'm doing it wrong. It takes 20 sec to perform this LINQ on 30 000 items, and under one sec using for-each loop. Below is working for-each loop, and my attempt to make LINQ of it (this one is slow). Linq solution is what I would like to have.

        For Each i As LengthAreaObject In myobjects
            For Each o As ObjectId In oidsToRem
                If i.oid = o Then
                    returnlist.Add(i)
                    oidsToRem.Remove(o)
                    Exit For
                End If

            Next
        Next

and LINQ attempt here

Dim rlist As List(Of LengthAreaObject) = (From i As LengthAreaObject In myobjects.AsParallel Where oidsToRem.Contains(i.oid) Select i).ToList

Upvotes: 0

Views: 321

Answers (2)

nekitip
nekitip

Reputation: 365

I have found similiar question on stackoverflow and modified it. So the solution to speed things up is nothing more but to hash collection where the objects are you test for "contains". Otherwise, contains is slow!

Dim setToRemove = New HashSet(Of ObjectId)(oidstoRem)
   Dim returnlist As List(Of LengthAreaObject) = lengthAreaList.AsParallel.Where(Function(x) setToRemove.Contains(x.oid)).ToList

Upvotes: 0

Fabio
Fabio

Reputation: 1980

How much items have the collections?

For small collections, AsParallel will be slower because of the extra method call.

Upvotes: 0

Related Questions