-1

I have below query where i am using the where clause with select and getting the result (list of librarySourceRowInputs) and would like to use the aggregate instead of (where and select).

In this process I am trying to access the same variables inside the aggregate but not getting any reference and below is the code for the same

public static LibrarySourceTableInput CreateLibrarySourceTableInput<T>(List<T> libraries, string mechanicalLibraryName)
       where T : ISourceOfData => new LibrarySourceTableInput()
{             
    LibrarySourceRowInputs = libraries?
                             .Where(l => l != null)
                             .Select(l => new LibrarySourceRowInput()
                             {
                                 LibrarySourceId = l.Id,
                                 SourceOfDataId = l.SourceOfData.Id
                             }).ToList() ?? new(),
    MappedLibrarySource = mechanicalLibraryName
};

below is the function where i am trying to use aggregate

// trying to replace the where and select in above with aggregate
 var LibrarySourceRowInputs = libraries.Aggregate(new List<LibrarySourceRowInput>(), 
 (prev, next) => 
        // here I am not getting any reference for Id
        );

I am not sure is this proper way to achieve this or any other way. Could any one please suggest any idea on this, many thanks in advance!

ggeorge
  • 328
  • 1
  • 2
  • 11
Enigma State
  • 16,494
  • 25
  • 86
  • 179

1 Answers1

0

I fix this issue by using aggregate like as below

 LibrarySourceRowInputs = libraries?.Aggregate(new List<LibrarySourceRowInput>(), 
 (acc, ids) =>
 {
     if (ids != null)
     {
         acc.Add(new LibrarySourceRowInput() { LibrarySourceId = ids.Id, 
                                               SourceOfDataId = ids.SourceOfData.Id });
     }
     return acc;
 })
Enigma State
  • 16,494
  • 25
  • 86
  • 179
  • which one is faster ? where and select or aggregate ? – Kosmas Mar 18 '21 at 04:05
  • You shouldn't use Aggregate if you're not actually aggregating and you just want to perform an action on each item for its side effects. The correct means of performing an action for its side effects on each item in a sequence is to use `foreach`. – Servy Mar 18 '21 at 15:07