0

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
PJDW
  • 145
  • 1
  • 4
  • 15

3 Answers3

2

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

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
2

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

Community
  • 1
  • 1
David Gregor
  • 1,855
  • 1
  • 13
  • 14
-1

I can be similar to this

var dataFields = dataFields .Where(f => relations.Any(r => f.SourceCollectionsID ==r.ChildCollectionID))
                .ToList()
I4V
  • 34,891
  • 6
  • 67
  • 79