PJDW
PJDW

Reputation: 145

C# foreach to linq

I was wondering if there wasn't an optimal way for this code.

List<CollectionFormFieldRecord> dataFields = new List<CollectionFormFieldRecord>();
foreach (CollectionRelationModel relation in relations)
{
     foreach (var field in visibleFields)
     {
          if (field.SourceCollectionsID == relation.ChildCollectionID)
            dataFields.Add(field);
     }
}

When a field (visibleFields) has a SourceCollectionsID that exists in the relations list then the field must be added to a separated list.

I tried somethings with LINQ but didn't know how to compare a property with a property in a list.

Upvotes: 0

Views: 211

Answers (3)

David Gregor
David Gregor

Reputation: 1885

The code you showed us has complexity of O(N square). Try to use .Join method, so you will have complexity close to O(N) due to hashing. The code you should use is

dataFields = visibleFields.Join(relations, vF => vF.SourceCollectionsID, r => r.ChildCollectionID, (visibleField, relation) => visibleField).ToList();

For better understand about complexity look at my answer for this question

Upvotes: 2

I4V
I4V

Reputation: 35353

I can be similar to this

var dataFields = dataFields .Where(f => relations.Any(r => f.SourceCollectionsID ==r.ChildCollectionID))
                .ToList()

Upvotes: -1

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

You can do this using linq

dataFields = (from relation in relations 
                    from field in visibleFields 
                    where field.SourceCollectionsID == relation.ChildCollectionID 
                    select field).Select(field => field).ToList();

but I do prefer using foreaches instead

Upvotes: 2

Related Questions